There is some ways to unwrap an optional value:
// 1st way
var str: String? = "Hello, playground"
if let strUnwrapped = str {
// strUnwrapped is immutable
println(strUnwrapped)
}
// 2nd way
var str: String? = "Hello, playground"
if var strUnwrapped = str {
// strUnwrapped is mutable
strUnwrapped = "Toldino"
println(strUnwrapped)
}
But I recently test this following one...
// The strangest one
var str: String? = "Hello, playground"
if let var strUnwrapped = str {
// strUnwrapped is mutabe
strUnwrapped = "yolo"
println(strUnwrapped)
}
Can you explain me why does it work ? It is a bug or a functionality ?
EDIT
As niñoscript said, it was a bug.
It is resolved in Swift 2.0, I tried it with the new version and it doesn't compile anymore.
Now Xcode throw this following error for "if let var"
A common way of unwrapping optionals is with if let syntax, which unwraps with a condition. If there was a value inside the optional then you can use it, but if there wasn't the condition fails.
You can unwrap optionals in 4 different ways: With force unwrapping, using ! With optional binding, using if let. With implicitly unwrapped optionals, using !
Implicitly unwrapped Optionals and normal Optionals are both Optionals, the difference being when accessing an implicitly unwrapped Optional, you confidently know that there is a valid value under the hood and ready for use. Normal Optionals need if let binding or a forced unwrapping ( ! )
This answer is only valid for Xcode 6, the bug was fixed in Xcode 7 as noted by the OP's edit and Paul Jarysta's answer
In this case:
if let var strUnwrapped = str {}
let var works the same way as just var, so either it is a bug or it's just the same thing. But if you try the following simple code:
let var n = 3
It throws this error:
'var' cannot appear nested inside another 'var' or 'let' pattern
So we can safely assume that it is a bug. We should be good developers and report it!
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