Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift optional inout parameters and nil

Tags:

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.

like image 202
devios1 Avatar asked Jul 11 '14 05:07

devios1


People also ask

How do you pass Inout parameters in Swift?

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.

What does Inout mean in Swift?

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.

How do you make a parameter optional in Swift?

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() .

What is Inout parameter?

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.


1 Answers

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)

like image 106
Bryan Chen Avatar answered Oct 19 '22 02:10

Bryan Chen