Toldy
Toldy

Reputation: 1251

If let var - Unwrapping optional value

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" xcode error

Upvotes: 8

Views: 8402

Answers (2)

NiñoScript
NiñoScript

Reputation: 4593

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!

Upvotes: 8

paullostj
paullostj

Reputation: 144

This problem was solved in xcode 7 ;-)

enter image description here

Upvotes: 3

Related Questions