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

穿精又带淫゛_ 提交于 2019-12-13 08:14:19

问题


This is my code

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
    }
}

This error shouldn't be thrown right? Every conforming instance of this protocol is a UIViewController, therefore a subclass of AnyObject. The compiler validates this, because when I add : AnyObject to my protocol, it compiles. BUT: Now I see an ugly error:

Redundant constraint 'Self' : 'AnyObject'

This is the compiling code (so with the compiler warning):

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

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

Is this some bug? I am using Xcode 10 and Swift 4.2.


回答1:


The problem is that this syntax is not supported:

public protocol MyProtocol where Self: UIViewController {

It compiles, sort of, but that fact is a bug. The correct syntax is to attach the where condition to the extension:

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



回答2:


To fix this error just mark giveMoney() function as mutating.

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

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


来源:https://stackoverflow.com/questions/52841954/where-self-uiviewcontroller-compiler-thinks-i-am-dealing-with-a-non-anyobjec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!