Swift - Optional Void

自作多情 提交于 2019-12-06 05:43:40

问题


I was busy using NSURLProtocolClient's URLProtocol function:

welf?.client?.URLProtocol(welf!, didReceiveResponse: operation.response, cacheStoragePolicy: NSURLCacheStoragePolicy.NotAllowed)

I was expecting it to return Void. But to my surprise it returns Void?

Why is it necessary to make a distinction between Void and Void?

I have read that Void is a type alias for the empty tuple type. So, does this have something to do with a distinction between the empty tuple type vs nil?


回答1:


This is simply because you are using Optional Chaining. The method returns Void, but it is possible for the whole chain to return nil before the method is ever called.

Essentially, a return value of Void will mean the call was actually made (self and client both have values) while a nil result will mean that one of those were nil.




回答2:


Note that, () and nil is different:

let a:Void? = ()
let b:Void? = nil

a == nil // -> false
b == nil // -> true

Using this, you can judge the method has really been invoked or not.

let result = welf?.client?.URLProtocol(welf!, didReceiveResponse: operation.response, cacheStoragePolicy: NSURLCacheStoragePolicy.NotAllowed)
if result != nil {
    // success
}
else {
    // `welf?.client` was `nil`
}


来源:https://stackoverflow.com/questions/26837951/swift-optional-void

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!