![](/img/trans.png)
[英]How is UIViewController automatically conforming to TableView protocols?
[英]How to use dynamic types conforming to protocols
我只是想了解為什么這是不可能的。 為什么不能在此設置中使用動態類型。 (我把它放在操場上):
protocol SomeProtocol {
init()
}
class SomeClass : SomeProtocol {
required init() { }
}
let x: SomeProtocol.Type = SomeClass.self
x()
運行此命令時,游樂場將崩潰,如果您嘗試將這樣的代碼放入Xcode中,它將拋出一個
命令由於信號失敗:分段錯誤:11
但是,如果我從不調用x()
,則可以將x打印為正確的SomeClass.Type。
我意識到這是一個奇怪的設置,所以我理解“為什么要這么做?”的困惑。 除此之外 可能嗎? 不可能? 是蟲子嗎? 我是否不了解協議的真正工作原理?
工作正常。 我在Xcode 7中嘗試了您的代碼,它可以編譯並運行。 當然,在實際代碼中,您不能在頂層說x()
。 在Swift 2中,您必須說x.init()
,而不是x()
。 但是,當您這樣做時,就可以了。
protocol SomeProtocol {
init()
}
class SomeClass : SomeProtocol {
required init() { }
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let x: SomeProtocol.Type = SomeClass.self
x.init()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.