Reputation: 571
I'm just trying to get a grasp as to why this isn't possible. Why can I not use a dynamic type with this setup. (I put this in playgrounds):
protocol SomeProtocol {
init()
}
class SomeClass : SomeProtocol {
required init() { }
}
let x: SomeProtocol.Type = SomeClass.self
x()
When this runs, playgrounds will crash, and if you try to put code like this in Xcode it will throw a
Command failed due to signal: Segmentation fault: 11
If I, however, never call x()
, I can print out x to be of the correct SomeClass.Type.
I realize this is a weird setup, so I understand the confusion of "why would you ever want to do that?". But that aside; is it possible? not possible? Is it a bug? Am I not understanding how protocols really work?
Upvotes: 0
Views: 89
Reputation: 534949
It works fine. I tried your code in Xcode 7 and it compiles and runs. Of course, in real code you can't say x()
at top level. And in Swift 2 you have to say x.init()
, not x()
. But when you do, it's fine.
protocol SomeProtocol {
init()
}
class SomeClass : SomeProtocol {
required init() { }
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let x: SomeProtocol.Type = SomeClass.self
x.init()
}
}
Upvotes: 1