Search code examples
swiftinitializationvariadic

Swift 2.2 - Using initialiser with variadic parameters of class type


In Swift 2.2, I have the following classes:

protocol Base {}

class FirstImpl: Base {}

class SecondImpl: Base {}

class Container {
    private var typeNames = Set<String>()

    init(_ types: Base.Type...) {
       for type in types {
           typeNames.insert(String(type))
       }
    }
}

If I only add a single class type to the Container, then it compiles fine:

let c = Container(FirstImpl)

But if I start adding more class types, then it will not compile:

let c = Container(FirstImpl, SecondImpl)

The build error is:

Cannot convert value of type '(FirstImpl, SecondImpl).Type' to expected argument type 'Base.Type'

Is it a limitation in the Swift compiler or am I doing something wrong?


Solution

  • It's a confusing error message, but the problem is that you need to use .self in order to refer to the types of your classes when passing them into a function. Therefore you'll want to do:

    let c = Container(FirstImpl.self, SecondImpl.self)
    

    Your first example that compiles without .self is in fact a bug (which has been resolved as of Swift 3) – see this Q&A for more info.