我试图用Swift编写一个泛型类,它的泛型类型既继承类又符合协议。但是,以下代码会导致编译器崩溃,导致分段错误: 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
}
}注释掉对协议属性的访问允许程序编译。如果没有编译器崩溃,就无法访问协议中的任何内容。创建像这样工作的泛型类有解决办法吗?
发布于 2014-09-25 20:09:20
正如MikeS所指出的那样,你应该打开一个雷达,以应对坠机事件。它不应该坠毁。
但是,解决方案是将重点放在实际需要T来遵守的协议(即方法列表)上,而不是在类中完成。例如:
protocol WhatGenericClassHolds : Protocol {
var classProperty: Any? { get }
}
class GenericClass<T: WhatGenericClassHolds> { ... }发布于 2014-09-25 20:27:33
你的声明有个问题。使类与协议一致,如下所示
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?.somePropertyhttps://stackoverflow.com/questions/26045077
复制相似问题