我有这样的协议(protocol)
public protocol FooProtocol {
associatedType someType
func doFoo(fooObject:someType) -> Void
}
我有一个实现这个协议(protocol)的类
public class Foo<T> : FooProtocol {
private let _doFoo : (T) -> Void
init<P : FooProtocol where P.someType == T>(_dep : P) {
_doFoo = _dep.doFoo
}
public func doFoo(fooObject: T) {
_doFoo(fooObject)
}
}
到这里为止的一切对我来说都很好,现在在另一个类中,我用 someType = MyType
实现了 FooProtocol ,然后当我尝试初始化 Foo
用T = MyType
上课通过 self
在 Foo
的初始化方法中类我得到一个编译错误,我在这里做错了什么?
错误信息:
" Cannot invoke init with an argument list of type
(_dep: NSObject -> () -> MyView)
"
public class MyView : UIViewController, FooProtocol {
func doFoo(fooObject : MyType) {
...
}
// Here I want to initialize the Foo<T> class
let fooInstant : Foo<MyType> = Foo.init(_dep : self)
// I get the error message on the above line the error
// message reads "Cannot invoke init with an argument list
// of type `(_dep: NSObject -> () -> MyView)`
}
是否自符合 FooProtocol someType == MyType
,因为我正在尝试初始化 Foo
对象 T == MyType
这在技术上应该可行吗?
最佳答案
这实际上似乎与您的泛型或协议(protocol)一致性没有任何关系。很简单,您试图在 self
初始化之前在您的属性分配中访问 self
(默认属性值是 在 初始化期间分配的)。
因此,解决方案是使用像这样的惰性属性:
lazy var fooInstant : Foo<MyType> = Foo(_dep : self)
这将在第一次访问时创建,因此在 self
初始化之后创建。
关于ios - 无法将自身(实现协议(protocol))传递给类实例化的 init 方法。(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36996573/