![](/img/trans.png)
[英]Is a blank function conventional in subclass that conforms to custom protocol?
[英]Swift generic class type both subclass and conforms to protocol
我正在嘗試在Swift中編寫泛型類,它的泛型類型都從類繼承並符合協議。 但是,以下代碼會導致編譯器因Segmentation fault而崩潰:11。
protocol Protocol {
var protocolProperty: Any? { get }
}
class Class {
var classProperty: Any?
}
class GenericClass<T: Class where T: Protocol> {
var genericProperty: T?
func foo() {
let classProperty: Any? = genericProperty!.classProperty
// This is the culprit
let protocolProperty: Any? = genericProperty!.protocolProperty
}
}
注釋掉對協議屬性的訪問允許程序編譯。 在沒有編譯器崩潰的情況下,無法從協議訪問任何內容。 是否有一種解決方法來創建一個像這樣工作的泛型類?
正如MikeS所說,你應該為墜機打開雷達。 它永遠不會崩潰。
但解決方案是專注於你真正需要T
符合的協議(即方法列表),而不是在課堂上被包裹起來。 例如:
protocol WhatGenericClassHolds : Protocol {
var classProperty: Any? { get }
}
class GenericClass<T: WhatGenericClassHolds> { ... }
您的聲明中存在問題。 使您的班級符合以下協議
protocol A {
var somePropertyInt : Int? {get }
}
class B:A {
var someProperty : String?
var somePropertyInt:Int?;
}
class GenericClass<T: B where T: A > {
var someGenericProperty : T?
func foo() {
println(someGenericProperty!.someProperty)
println(someGenericProperty!.somePropertyInt)
}
}
var someGen = GenericClass()
someGen.someGenericProperty?.somePropertyInt
someGen.someGenericProperty?.someProperty
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.