5

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?

2
  • As drewag says. Looking at the documentation confirms the return type (there is no mention of an optional return value). Commented Nov 10, 2014 at 6:41
  • I was also surprised. In my case I was passing a closure like { some?.call() } and Swift complained since the receiving parameter was expecting a function of type () -> () but that closure had an implicit type of () -> ()?. I finally casted the closure to () -> () but I don't know if this is correct. Commented Aug 21, 2017 at 14:33

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is actually a very nice tip! Thanks. Where did you learn about this?
6

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`
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.