哪里Self:UIViewcontroller->编译器认为我正在处理一个非AnyObject实例

时间:2018-10-16 18:36:20

标签: swift protocols

这是我的代码

public protocol MyProtocol where Self: UIViewController {
    var money: Int { get set }
}

public extension MyProtocol {
    func giveMoney() { // <-- ERROR: Left side of mutating operator isn't mutable: 'self' is immutable
        money += 1
    }
}

不应该抛出此错误吗?该协议的每个符合实例都是UIViewController,因此是AnyObject的子类。编译器对此进行了验证,因为当我在协议中添加: AnyObject时,它将进行编译。但是:现在我看到一个难看的错误:

  

冗余约束'Self':'AnyObject'

这是编译代码(因此带有编译器警告):

public protocol MyProtocol: AnyObject where Self: UIViewController {
    var money: Int { get set }
}

public extension MyProtocol {
    func giveMoney() {
        money += 1
    }
}

这是一些错误吗?我正在使用Xcode 10和Swift 4.2。

2 个答案:

答案 0 :(得分:4)

问题是不支持此语法:

public protocol MyProtocol where Self: UIViewController {

它可以编译,但是that fact is a bug。正确的语法是将where条件附加到扩展名:

public protocol MyProtocol  {
    var money: Int { get set }
}
public extension MyProtocol where Self: UIViewController {
    func giveMoney() { 
        money += 1
    }
}

答案 1 :(得分:1)

要解决此错误,只需将giveMoney()函数标记为mutating

public protocol MyProtocol where Self: UIViewController {
    var money: Int { get set }
}

public extension MyProtocol {
    mutating func giveMoney() {
        money += 1
    }
}