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 { ... } }
...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.
Swift inout parameter is a parameter that can be changed inside the function where it's passed into. To accept inout parameters, use the inout keyword in front of an argument. To pass a variable as an inout parameter, use the & operator in front of the parameter.
You write an in-out parameter by placing the inout keyword right before a parameter's type. An in-out parameter has a value that's passed in to the function, is modified by the function, and is passed back out of the function to replace the original value.
An Optional is a variable that can be nil , that's it. If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil . If your function looks like this func test(param: Int?) , you can't call it like this test() .
inout means that modifying the local variable will also modify the passed-in parameters. Without it, the passed-in parameters will remain the same value. Trying to think of reference type when you are using inout and value type without using it.
It won't compile because the function expecting a reference but you passed nil
. The problem have nothing to do with optional.
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
?
You need to call it like
var a : MyClass? = nil testFunc(&a) // value of a can be changed inside the function
If you know C++, this is C++ version of your code without optional
struct MyClass {}; void testFunc(MyClass &p) {} int main () { testFunc(nullptr); }
and you have this error message
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With