Search code examples
swift

Why can't I initialize this set?


var startset=Set<String>("asdasd","sadad")

Error:

Missing argument label 'arrayLiteral:' in call


I am inspired by this:

var ok=String("sdsf")

which prints "sdsf"


Solution

  • You can do that with String because it just so happens that String has an initialiser:

    public init<S>(_ other: S) where S : LosslessStringConvertible, S : Sequence, S.Element == Character
    

    String fits all the constrains of S, so it can be passed to this initialiser, and you are able to create a string this way.

    Set is a totally different class, and it doesn't have any initialiser to which you can pass 2 Strings, so you can't create a set by passing 2 strings.

    If you want to create a set with 2 strings as its elements, you can use an array literal:

    let set: Set<String> = ["asdasd","sadad"]
    

    Alternatively, if you want to call an initialiser explicitly,

    let set = Set<String>(["asdasd","sadad"])