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