Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type cast optional values

Tags:

swift

Whenever we need to du something with an optional value in swift we need to unwrap it to operate, not on the optional, but on the value ”inside” the optional.

var optionalString:String? = "Hello"
optionalString!.append(" World!")

Note the exclamation mark on the second line.

But when using the optional type cast operator (as?) on an optional value, one does not need to unwrap the optional, we just provide it with the optional itself, and it just magically works.

let sneakyString:Any? = "Hello!"
let notSoSneakyString = sneakyString as? String

Note the absent exclamation mark on the second line.

The magic is a bit more obvious if we spell it out:

let sneakyString:Any? = Optional("Hello")
let notSoSneakyString = sneakyString as? String

Its not a string we're trying to cast but an enum with a string as an associated value.

I would expect that I would have to do this:

let sneakyString:Any? = "Hello!"
let notSoSneakyString = sneakyString! as? String

Note the exclamation mark on the second line.

Does the type cast operators act on optionals and non optionals in the same way?

like image 805
weenzeel Avatar asked Aug 27 '16 20:08

weenzeel


People also ask

What are optional values?

An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark ( ? ) after the type of a value to mark the value as optional. Why would you want to use an optional value?

Is Optional A type in Swift?

An Optional is a type on its own, actually one of Swift 4's new super-powered enums. It has two possible values, None and Some(T), where T is an associated value of the correct data type available in Swift 4.

How do you change optional in Swift?

// Swift program to convert an optional string // into the normal string import Swift; var str:String=""; print("Enter String:"); str = readLine()!; print("String is: ",str); Output: Enter String: Hello World String is: Hello World ... Program finished with exit code 0 Press ENTER to exit console.


1 Answers

The as? operator makes a cast if it possibly can, and returns either the casted object or nil. It handles nil values too, so that if sneakyString were nil, you wouldn't have been able to cast it to a String and the cast would have failed. Same behaviour as if it were non-nil but not castable to String.

In other words, you don't need the ! because as? handles nil values automatically itself.

like image 84
HughHughTeotl Avatar answered Sep 23 '22 16:09

HughHughTeotl