我正在尝试使用子类化和协议一致性为类初始化Generic,但我无法做到,XCode对它不满意。
这是我的代码的一个更简单(测试)的例子:
import Foundation
// Definition of my protocol, adding a required initializer to a class
public protocol Protocol {
init(foo:Int, bar:Int)
}
// This is a much simpler class supposed to represent the Realm Object base class
// making it possible to reproduce the problem
// To be more accurate, you can import RealmSwift and replace it with Object
// but actually the problem can be reproduce with any class with subclassing
class FakeRealmObject: NSObject {
// Object stuff
}
// This is my class subclassing the Realm Object, defining a data model
final class Model: FakeRealmObject {
// Model stuff
}
// This is the extension of my class Model, conforming to my protocol Protocol
// This is the initializer i'd like to use as a generic
extension Model: Protocol {
convenience init(foo:Int, bar:Int) {
self.init()
// do stuff
println("it works \(foo)")
}
}
// This is the final class using generics.
// Goal is to be able to use any of my model classes as a parameter
class Test<T: FakeRealmObject where T: Protocol> {
func someMethod() {
let instance = T(foo: 1, bar: 2)
}
}
举个例子,你可以用:
进行测试let test = Test<Model>()
test.someMethod()
您会注意到let instance = T(foo: 1, bar: 2)
行
extra argument 'foo' in call
根据我的试验,我也得到了
Cannot find an initializer for type 'T' that accepts an argument list of type '(foo:Int, bar:Int)'
事情是,如果你删除类NSObject
中的FakeRealmObject
的子类,错误就会消失,一切都按预期工作。
当然,使用Realm中真正的Object
类,您无法做到这一点。
为了完全准确,在深入了解Realm时,我们可以看到Object
定义:
class Object : RLMObjectBase, Equatable, Printable
和RLMObjectBase
:
class RLMObjectBase : NSObject
我尝试了许多方法来找到解决方案,但到目前为止还没有任何工作,我依赖于Realm,当然我无法修改。
我的设计糟糕吗?如果是,那么正确的方法是什么? 这是代码/编译器的一个更深层次的问题吗?在尝试寻找解决方案时,我遇到了一些段错误,这绝对不是好事。