Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If let var - Unwrapping optional value

Tags:

ios

swift

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

like image 717
Toldy Avatar asked Jun 05 '15 13:06

Toldy


People also ask

What can be used to unwrap value inside optional?

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.

How many ways unwrap optional?

You can unwrap optionals in 4 different ways: With force unwrapping, using ! With optional binding, using if let. With implicitly unwrapped optionals, using !

What is the difference between unwrapping an optional with with and with implicit unwrapping?

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 ( ! )


1 Answers

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!

like image 152
NiñoScript Avatar answered Sep 23 '22 12:09

NiñoScript