其中 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
添加到我的协议时,它会编译.但是:现在我看到一个丑陋的错误:
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:
冗余约束 'Self' : 'AnyObject'
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
}
}
这是bug吗?我使用的是 Xcode 10 和 Swift 4.2.
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 {
它可以编译,有点,但这个事实是一个错误.正确的语法是将 where 条件附加到扩展名:
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
}
}
这篇关于其中 Self: UIViewcontroller ->编译器认为我正在处理一个非 AnyObject 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!