更新时间:2023-11-27 17:44:22
当你在声明时将一个 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