作者:和雅竹 | 来源:互联网 | 2022-12-08 17:42
我很好奇为什么这不起作用:
public protocol MyProtocol {
var i: Int { get set }
}
public protocol MyProtocol2: class, MyProtocol {}
public extension MyProtocol2 where Self: AnyObject {
func a() {
i = 0 <-- error
}
}
错误:
无法分配属性:'self'是不可变的
为什么?只有类可以采用MyProtocol2.如果我: class
在MyProtocol后面添加声明它可以工作.我不明白为什么它不适用于子协议.
1> Hamish..:
您的示例不编译,因为MyProtocol
它不是类绑定的,因此可以有mutating
需求和扩展成员.这包括属性设置器,默认情况下mutating
.这些成员可以自由地重新分配一个全新的值self
,这意味着编译器需要确保它们被调用可变变量.
例如,考虑:
public protocol MyProtocol {
init()
var i: Int { get set } // implicitly `{ get mutating set }`
}
extension MyProtocol {
var i: Int {
get { return 0 }
// implicitly `mutating set`
set { self = type(of: self).init() } // assign a completely new instance to `self`.
}
}
public protocol MyProtocol2 : class, MyProtocol {}
public extension MyProtocol2 where Self : AnyObject {
func a() {
i = 0 // error: Cannot assign to property: 'self' is immutable
}
}
final class C : MyProtocol2 {
init() {}
}
let c = C()
c.a()
如果这是合法的,则调用c.a()
将为C
变量重新分配一个全新的实例c
.但是c
是不可变的,因此代码没有很好地形成.
使MyProtocol
类绑定(即protocol MyProtocol : AnyObject
或不推荐的拼写protocol MyProtocol : class
)有效,因为现在编译器知道只有类可以符合MyProtocol
.因此,它通过禁止mutating
要求和扩展成员来强制引用语义,因此可以防止任何突变self
.
您可以使用的另一个选项是将需求的标记符标记i
为nonmutating
- 因此意味着它只能由非变异的setter满足.这使您的代码再次格式良好:
public protocol MyProtocol {
init()
var i: Int { get nonmutating set }
}
public protocol MyProtocol2 : class, MyProtocol {}
public extension MyProtocol2 where Self : AnyObject {
func a() {
i = 0 // legal
}
}