Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
instantiate-from-class.swift
protocol P {
static var name: String { get }
init(i:Int)
}
class A: P {
static var name: String {
get { return "A" }
}
required init(i:Int) {}
}
class B: P {
static var name: String {
get { return "B" }
}
required init(i:Int) {}
}
let clsA:P.Type = A.self
let a:P = clsA(i:1)
print("a.dynamicType.name = \(a.dynamicType.name)")
let clsB:P.Type = B.self
let b:P = clsB(i:1)
print("b.dynamicType.name = \(b.dynamicType.name)")
@brentsimmons

This comment has been minimized.

Copy link

@brentsimmons brentsimmons commented Jul 20, 2015

I get the same error I get with my own try:

Playground execution failed: /var/folders/8h/4kb_c3716638fqs4k9mxnpfc0000gn/T/./lldb/1603/playground1222.swift:20:15: error: initializing from a metatype value must reference 'init' explicitly
let a:P = clsA(i:1)
^
.init

@wilshipley

This comment has been minimized.

Copy link

@wilshipley wilshipley commented Jul 20, 2015

On the latest Swift you have to add the word "init" to make this more explicit. Then it works. e.g:

let a:P = clsA.init(i:1)
...
let b:P = clsB.init(i:1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment