Jee*_*eef 13 protocols ios swift
我正在寻找一种通过协议扩展为协议添加默认初始化程序的方法.
我的协议是:
protocol TestProtocol {
var myVar : Double { get set }
init(value: Double)
init(existingStruct : TestProtocol)
}
Run Code Online (Sandbox Code Playgroud)
我使用这个协议实现了一个结构:
struct TestStruct : TestProtocol {
var myVar : Double
init(value : Double) {
myVar = value
}
init (existingStruct : TestProtocol) {
myVar = existingStruct.myVar
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试通过扩展来为此协议创建默认初始化程序,我会遇到自我问题:
extension TestProtocol {
init(value : Double) {
myVar = value
}
init(existingStruct : TestProtocol) {
myVar = existingStruct.myVar
}
}
Run Code Online (Sandbox Code Playgroud)
两个赋值行在初始化之前发出错误 变量'self'通过引用传递
有没有办法让这项工作 - 或者我只限于使用课程?

Dev*_*ist 24
你的问题几乎和我昨天回答的这篇文章一样.
这是解决这个问题的诀窍:)
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
}
}
Run Code Online (Sandbox Code Playgroud)
祝你有美好的一天.:)协议扩展非常好.
| 归档时间: |
|
| 查看次数: |
7053 次 |
| 最近记录: |