Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Purpose of "an Optional of an Optional" in Swift Optional Types?

I found an interesting function in the Swift Tests source code:

func test(_ v: A????, _ cast: (A????) -> B?)

Since Type? is just syntax sugar for Optional<Type>, this means that the type of the argument v can be rewritten as Optional<Optional<Optional<Optional<A>>>>.

I know that this function is used to test optional types, so it is definitely going overboard with the arguments v and cast, but what would be the actual use of having "an optional of an an optional, etc." type in Swift (if any)?

like image 453
Wilson Gramer Avatar asked Oct 16 '22 19:10

Wilson Gramer


1 Answers

These occur sometimes in Swift when you are accessing data.

One example is if you have a dictionary with an optional type for the value, and then you look up a value in that dictionary:

let rockStars: [String: String?] = ["Sting": nil, "Elvis": "Presley", "Bono": nil, "Madonna": nil]

let lastName = rockStars["Elvis"]
print(lastName as Any)
Optional(Optional("Presley"))

This happens because a dictionary look up can fail when the key is not present, and it returns nil in that case. So the return type of a dictionary lookup has to be the value type wrapped in an optional. A look up from the rockStars dictionary returns a String??.

like image 176
vacawama Avatar answered Nov 15 '22 12:11

vacawama