Created
July 20, 2015 03:29
-
-
Save tjw/4f3ea2be02e5877746aa to your computer and use it in GitHub Desktop.
instantiate-from-class.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)") |
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
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