Swift optional inout parameters and nil

option-type, swift

Solution

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)

Problem

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.

Original source