Swift可选inout参数和nil

dev*_*os1 19 optional swift

是否可以Optional inout在Swift中为函数提供参数?我想这样做:

func testFunc( inout optionalParam: MyClass? ) {
    if optionalParam {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

...但是当我尝试调用它并通过时nil,它给了我一个奇怪的编译错误:

Type 'inout MyClass?' does not conform to protocol 'NilLiteralConvertible'
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我的类在已经被声明为可选时必须符合某些特殊协议.

Bry*_*hen 28

它不会编译因为函数需要引用但是你通过了nil.这个问题与可选问题无关.

通过声明参数,inout意味着您将在函数体内为其指定一些值.它如何赋值nil

你需要称之为

var a : MyClass? = nil
testFunc(&a) // value of a can be changed inside the function
Run Code Online (Sandbox Code Playgroud)

如果您了解C++,那么这是您的代码的C++版本,没有可选项

struct MyClass {};    
void testFunc(MyClass &p) {}
int main () { testFunc(nullptr); }
Run Code Online (Sandbox Code Playgroud)

并且您有此错误消息

main.cpp:6:6: note: candidate function not viable: no known conversion from 'nullptr_t' to 'MyClass &' for 1st argument
Run Code Online (Sandbox Code Playgroud)

这有点像你得到的(但更容易理解)


Sla*_*off 5

实际上@devios1需要的是“可选指针”。但在 MyClass 中呢?意思是“指向可选的指针”。以下内容应该适用于 Swift 4

class MyClass {
    // func foo() {}
}

func testFunc(_ optionalParam: UnsafeMutablePointer<MyClass>? ) {
    if let optionalParam = optionalParam {
        // optionalParam.pointee.foo()
        // optionalParam.pointee = MyClass()
    }
}

testFunc(nil)

var myClass = MyClass()
testFunc(&myClass)
Run Code Online (Sandbox Code Playgroud)