使Swift类符合需要init的协议

时间:2014-11-11 23:58:57

标签: cocoa swift protocols

我在protocol中有以下Swift

protocol FooConvertible{
    typealias FooType

    init(foo: FooType)
}

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

class Bar: FooConvertible {
    var baz: String = ""
    required init(foo: String){
        baz = foo
    }
}

到目前为止一切顺利。然而,当我试图让一个类在扩展中符合它时出现了问题(使用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

    }
}

这个used to be possible,在以前版本的语言

删除它的原因是什么?

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

1 个答案:

答案 0 :(得分: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
    }
}

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