问题描述
在Swift中是否可以为函数使用Optional
inout
参数?我正在尝试这样做:
Is it possible to have an Optional
inout
parameter to a function in Swift? I am trying to do this:
func testFunc( inout optionalParam: MyClass? ) {
if optionalParam {
...
}
}
...但是当我尝试调用它并传递nil
时,它给了我一个奇怪的编译错误:
...but when I try to call it and pass nil
, it is giving me a strange compile error:
Type 'inout MyClass?' does not conform to protocol 'NilLiteralConvertible'
我不知道为什么我的类已经被声明为可选的,所以必须遵循某些特殊的协议.
I don't see why my class should have to conform to some special protocol when it's already declared as an optional.
推荐答案
它不会编译,因为该函数需要引用,但是您已通过nil
.问题与可选无关.
It won't compile because the function expecting a reference but you passed nil
. The problem have nothing to do with optional.
通过用inout
声明参数意味着您将在函数体内为其分配一些值.如何为nil
赋值?
By declaring parameter with inout
means that you will assign some value to it inside the function body. How can it assign value to nil
?
您需要这样称呼
var a : MyClass? = nil
testFunc(&a) // value of a can be changed inside the function
如果您了解C ++,这是您的代码的C ++版本,没有可选内容
If you know C++, this is C++ version of your code without optional
struct MyClass {};
void testFunc(MyClass &p) {}
int main () { testFunc(nullptr); }
您收到此错误消息
main.cpp:6:6: note: candidate function not viable: no known conversion from 'nullptr_t' to 'MyClass &' for 1st argument
相当于您所拥有的(但更容易理解)
which is kind of equivalent to the on you got (but easier to understand)
这篇关于Swift可选的inout参数和nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!