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)?
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??
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With