使Swift类符合需要init的协议

cfi*_*her 6 cocoa protocols swift

我有以下protocolSwift:

protocol FooConvertible{
    typealias FooType

    init(foo: FooType)
}
Run Code Online (Sandbox Code Playgroud)

我可以Swift在类定义中使类符合它:

class Bar: FooConvertible {
    var baz: String = ""
    required init(foo: String){
        baz = foo
    }
}
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.但是,当我尝试在扩展中使类符合它时出现问题(使用Cocoa类,这是我唯一的选择,因为我没有源代码):

class Baz {
    var baz = ""
}

extension Baz: FooConvertible{

    required convenience init(foo: String) { // Insists that this should be in the class definition
        baz = foo
    }
}

extension NSURL: FooConvertible{

    required convenience init(foo: String) { // this also fails for the same reason

    }
}
Run Code Online (Sandbox Code Playgroud)

在以前的语言版本中,这曾经是可能

它被删除的原因是什么?

这意味着所有XXXLiteralConvertible协议都被禁止使用Cocoa类!

Dev*_*ist 1

如果您有机会尝试创建这样的东西:

protocol FooConvertible : class {
    typealias FooType

    var baz : String { get set } // protocol extensions inits may need to know this

    init(foo: FooType) // this is your designated initializer
}

extension FooConvertible {

    // init(foo: String) {
    //     self.init(foo: foo)
    //     baz = foo
    // }
    // you can't do this because it could call it self recursively 

    init(num: Int) { // this init will call your designated init and can instantiate correctly 
        self.init(foo: "\(num)")
    }
}

class Baz {
    var baz = ""
}

class Bar: FooConvertible {
    var baz: String = ""

    required init(foo: String) { // designated initializer
        baz = foo
    }
}
Run Code Online (Sandbox Code Playgroud)

Baz现在将了解 的所有 init FooConvertible。如果是这样,我很高兴能提供帮助。:)