传递给类实例化的init方法

传递给类实例化的init方法

本文介绍了无法将self(实现协议)传递给类实例化的init方法.(Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的协议

public protocol FooProtocol {
    associatedType someType

    func doFoo(fooObject:someType) -> Void
}

我有一个实现此协议的类

I have a class that implements this 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,然后当我尝试通过在T = MyType的init方法中传递self来初始化Foo类时,使用T = MyType Foo类我收到编译错误,我在这里做什么错了?

Everything upto here looks good to me, Now in another class I implement the FooProtocol with someType = MyType, then when I try to initialize the Foo class with T = MyType by passing self in the init method of the Foo class I get a compilation error, what am I doing wrong here?

错误消息:

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)`
}

使用someType == MyType是否不符合FooProtocol,并且由于我试图使用T == MyType初始化Foo对象,因此从技术上讲应该可以吗?

Isn't self conforming to FooProtocol with someType == MyType, and since I am trying to init a Foo object with T == MyType this should technically work yes?

推荐答案

实际上,这似乎与您的泛型或协议一致性无关.仅仅是因为您要在初始化self之前尝试在属性分配中访问self(在初始化期间 分配了默认属性值).

This actually doesn't appear to be anything to do with your generics or protocol conformance. It's simply that you're trying to access self in your property assignment before self has been initialised (default property values are assigned during initialisation).

因此,解决方案是像这样使用惰性属性:

The solution therefore is to use a lazy property like so:

lazy var fooInstant : Foo<MyType> = Foo(_dep : self)

现在将在首次访问时创建它,因此在初始化self之后.

This will now be created when it's first accessed, and therefore after self has been initialised.

这篇关于无法将self(实现协议)传递给类实例化的init方法.(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:33