【问题标题】:Swift protocol extension self reference issues with initSwift 协议扩展自引用问题与 init
【发布时间】:2015-06-15 12:22:43
【问题描述】:

我正在寻找一种通过协议扩展向协议添加默认初始化程序的方法。

我的协议是:

protocol TestProtocol {
    var myVar : Double { get set }
    init(value: Double)
    init(existingStruct : TestProtocol)
}

我已经使用这个协议实现了一个结构:

struct TestStruct : TestProtocol {
    var myVar : Double

    init(value : Double) {
        myVar = value
    }

    init (existingStruct : TestProtocol) {
        myVar = existingStruct.myVar
    }
}

但是,如果我尝试通过 extension 为该协议创建默认初始化程序,我会遇到自我问题:

extension TestProtocol {
    init(value : Double) {
        myVar = value
    }

    init(existingStruct : TestProtocol) {
        myVar = existingStruct.myVar
    }
}

两个赋值行都发出错误 变量“self”在初始化之前通过引用传递

有没有办法让这项工作 - 或者我仅限于使用类?

【问题讨论】:

  • 那个 xcode 是 monokai 主题的吗?我要它!
  • 各位大神,如何保证采用TestProtocol的具体类型完全被协议扩展中的inits初始化?特别是对于值类型(即:结构或枚举)。
  • @MatteoPiombo 没有什么是不可能的 :) 我将发布解决方案作为这个问题的答案。

标签: ios swift protocols


【解决方案1】:

您的问题与我昨天回答的post 几乎相同。

这是解决这个问题的诀窍:)

protocol TestProtocol {
    var myVar : Double { get set }
    init() // designated initializer which will ensure that your class or structer type will instantiate correctly
}

struct TestStruct : TestProtocol {
    var myVar : Double

    init() {
        myVar = 0
    }
}

extension TestProtocol {
    init(value : Double) {
        self.init()
        myVar = value
    }

    init(existingStruct : TestProtocol) {
        self.init()
        myVar = existingStruct.myVar
    }
}

祝你有美好的一天。 :) 协议扩展太好了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多