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

where Self: UIViewcontroller -> Compiler thinks I am dealing with a non-AnyObject instance

这是我的代码

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 添加到我的协议时,它会编译。但是:现在我看到一个丑陋的错误:

Redundant constraint '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.

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

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

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

问题是不支持这种语法:

public protocol MyProtocol where Self: UIViewController {

它编译,有点,但是 。正确的语法是将 where 条件附加到扩展名:

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