Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

Swift optional inout parameters and nil

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...