Skip to content

Instantly share code, notes, and snippets.

@tjw
Created July 20, 2015 03:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjw/4f3ea2be02e5877746aa to your computer and use it in GitHub Desktop.
Save tjw/4f3ea2be02e5877746aa to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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