【发布时间】:2017-04-07 01:55:56
【问题描述】:
这是代码,
protocol TestType : AnyObject {
}
class Generic<TestType> : NSObject {
private let filterFunction : (TestType,String) -> Bool
init(filter: @escaping (TestType,String) -> Bool) {
filterFunction = filter
}
}
class Parent : UIViewController {
public var generic : Generic<TestType>!
}
class Child : Parent {
override func viewDidLoad() {
// ERROR THIS LINE
generic = Generic<Object>(filter: { (str1, str2) -> Bool in
return true
})
}
}
class Object : TestType {
}
错误是:
Cannot assign value of type 'Generic<Object>' to type 'Generic<TestType>!'
我尝试了很多东西,比如 typealias,但无法编译代码。
问题是我不想要 Parent<TestType> 或 Child<TestType> 类,因为我希望能够在 IB 中使用它。
我如何在 Parent 中存储 Generic 的引用,并在 Child 中初始化它(动态地,通过设置具体的 TestType,如 Object 或其他)
【问题讨论】:
-
比较 Swift generic coercion misunderstanding 和 How do I store a value of type Class<ClassImplementingProtocol> in a Dictionary of type [String:Class<Protocol>] in Swift? -
Generic<Object>不能转换为Generic<TestType>。 -
为什么不直接创建一个
Generic<TestType>实例? -
谢谢@Hamish,你的帖子很有帮助。在我的代码中,Parent Class 是具有一些搜索功能的扩展 TableviewController。我希望我的子控制器继承这些功能,并根据这些项目将项目列表和过滤器提供给父视图控制器以正常工作。
-
好的,但我的意思是为什么不在
Child中创建一个Generic<TestType>?假设您的过滤器函数应该忽略不属于Object类型的参数,您总是可以在谓词中添加guard let object = str1 as? Object else { return false }。如果您让我们了解您实际使用Generic的用途,将会有所帮助。