问题描述
以下代码:
protocol SomeProtocol {}
class SomeClass: SomeProtocol {}
private func doSomethingWith(inout someVar: SomeProtocol) {}
private var someGlobalVar = SomeClass() // inferring SomeClass's type
doSomethingWith(&someGlobalVar)
产生以下错误:
无法使用类型为(inout SomeClass)"的参数列表调用doSomethingWith"
将倒数第二行更改为 private var someGlobalVar: SomeProtocol = SomeClass()
可解决错误.
Changing the penultimate line to private var someGlobalVar: SomeProtocol = SomeClass()
resolves the error.
主题
推荐答案
当你在声明时将一个 SomeClass
实例分配给一个变量,变量类型被推断为 SomeClass
.和写作一样
When you assign a SomeClass
instance to a variable while declaring, the variable type is inferred to be SomeClass
. The same as writing
private var someGlobalVar: SomeClass = SomeClass()
但是,当传递给 inout
参数时,该函数可以将另一个实例分配给该变量,例如
However, when passing to an inout
parameter, the function can assign another instance to that variable, e.g.
private func doSomethingWith(inout someVar: SomeProtocol) {
someVar = OtherClass()
}
现在你有一个类型不匹配.您看到的错误是 Swift 阻止您遇到类似问题.
Now you have a type mismatch. The error you are seeing is Swift preventing you getting a similar problem.
换句话说:如果您将一个变量传递给一个函数,并且您知道该函数可以将采用 SomeProtocol
的任何实例分配给该变量,那么您必须使用一个实际上可以保存任何采用SomeProtocol
的实例:
In other words: if you are passing a variable to a function and you know that the function can assign any instance adopting SomeProtocol
to that variable, you have to use a variable that can actually hold any instance adopting SomeProtocol
:
private var someGlobalVar: SomeProtocol
这篇关于协议类型的 inout 变量是否被禁止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!