简体   繁体   中英

Accessing valueless implicitly unwrapped optional?

I am curious about the way implicitly unwrapped optionals work, in the Apple reference book - The Swift Programming Language it states:

“If you try to access an implicitly unwrapped optional when it does not contain a value, you will trigger a runtime error. The result is exactly the same as if you place an exclamation mark after a normal optional that does not contain a value.”

If I try and access a valueless optional without an exclamation mark you get an error as stated above.

var optionalVar:String?
println("VAR: \(optionalVar!)")

If however you try an access an implicitly unwrapped optional that does not contain a value the println outputs VAR: nil which is not what is stated above.

var implicitOpt:String!
println("VAR: \(implicitOpt)")

Can anyone clarify this, is it badly worded docs, me miss understanding, a bug?

Thing is that you are not unwrapping the value in this case, but printing unwrapped optional as special type. Weird, I know. Try casting it to normal String and it will crash if nil :

var implicitOpt: String!
println("VAR: \(implicitOpt as String)")

The following lines are equal:

var implicitOpt: ImplicitlyUnwrappedOptional<String>
var implicitOpt: String!

ImplicitlyUnwrappedOptional conforms to Printable protocol. So the string interpolation

"\(implicitOpt)"

will call description on ImplicitlyUnwrappedOptional instance and not String instance. Thats why optional is not unwrapped in this case.

When you define it as a implicitly unwrapped optional ,the compiler expects it to be initialised and already holding a value .

If you try to do any operation on the variable it will throw you a run time error . You can observe that evaluation doesn't throw any runtime error ,it will give you nil (look at the if loop where it is evaluated)

var implicitOpt:String!
print("VAR: \(implicitOpt)")


var someValue = 10;

if let x = implicitOpt
{
    someValue=1;
}
else
{
    someValue=2
}


var b = implicitOpt;

b = b + "asdf"

let a = implicitOpt + "asdf"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM