ios - 无法将自身(实现协议(protocol))传递给类实例化的 init 方法。(Swift)

标签 ios swift swift2 swift-protocols

我有这样的协议(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 ,然后当我尝试初始化 FooT = MyType上课通过 selfFoo 的初始化方法中类我得到一个编译错误,我在这里做错了什么?

错误信息:

" 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/

相关文章:

ios - 播放用 AVFoundation 录制的视频

iPad 上的 iPhone 应用程序在首次启动时不响应触摸

iOS - UINavigationController - NavigationBar 与 UIViewController 一起滑入

iphone - 合并两个 UIImages 比 CGContextDrawImage 更快

ios - 使用 Swiftly JSON 解析 JSON

swift - 更改 print(Object) 在 Swift 2.0 中显示的内容

ios - 让 "didSelectRowAtIndexPath"仅在点击单元格内的图像时不调用(但在其他情况下调用)?

ios - 如何在 swift 中以编程方式创建动态标签大小?

swift - 在 UITableView 中存储单个 UISwitch 状态

ios - 我怎样才能防止用户点击按钮两次,这样当用户关闭应用程序并打开他仍然无法点击