Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-12027] Array literal declaration for mixed implicit literal initializers doesn't take type into consideration #54464

Open
BenchR267 opened this issue Jan 14, 2020 · 2 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. compiler The Swift compiler in itself

Comments

@BenchR267
Copy link
Member

Previous ID SR-12027
Radar rdar://problem/58565903
Original Reporter @BenchR267
Type Bug
Environment

This happens in a recent Swift compiler but is probably not limited to that version.

Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: 751621a4d7f44f5a92aa26c4559a03c2

Issue Description:

I have code similar to the following snippet:

enum Foo: ExpressibleByArrayLiteral, ExpressibleByStringLiteral {
    case arr([String])
    case str(String)
    
    init(stringLiteral value: String) {
        self = .str(value)
    }
    
    init(arrayLiteral elements: String...) {
        self = .arr(elements)
    }
}

This type can either represent an array of strings or a string and it should be possible to initialize it with either an array literal (of strings) or a string literal. I want to use those initializers implicitly by declaring an array of Foo like that:

let foos: [Foo] = [
    [],
    ["a"],
    "a",
]

Having the [Foo] array only contain array literals works fine, only strings works fine as well but having both requires me to add `as Foo` to either all strings or all arrays. It seems that there's a bug in the evaluation of the literal's type which doesn't take the declaration context into consideration.

@theblixguy
Copy link
Collaborator

Hmm, feels like a bug as the inferred type depends on which element comes first. In the meantime, here's a possible workaround:

enum Foo: ExpressibleByArrayLiteral, ExpressibleByStringLiteral {
  case arr([String])
  case str(String)

  init(stringLiteral value: String) {
    self = .str(value)
  }

  init(arrayLiteral elements: Foo...) {
    self = .arr(elements.compactMap {
      if case let .str(value) = $0 {
        return value
      }
      return nil
    })
  }
}

let foos: [Foo] = [[], ["a"], "a"]

@beccadax
Copy link
Contributor

@swift-ci create

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. compiler The Swift compiler in itself
Projects
None yet
Development

No branches or pull requests

3 participants