LoginSignup
38
36

More than 5 years have passed since last update.

Swift1.2で複数の変数を1度にOptional Bindingできるように

Posted at

Xcode6.3betaのリリースに伴い、Swift1.2がリリースされましたね。

Swift1.2の仕様を見ていると、複数の変数のOptional Bindingを1行で書けるようになったらしいですね。

Swift1.1までは複数の変数のOptional Bindingの代替として、この記事のような方法がありました。

~swift1.1
let first : Int? = "1".toInt()
let second : Int? = "2".toInt()

switch (first, second) {
case (.Some(let f), .Some(let s)):
    println(f + s)
default:
    println("error")
}

また、それ以外の方法として複数の変数のOptional Bindingをやる場合、

~swift1.1
let first : Int? = "1".toInt()
let second : Int? = "2".toInt()

if let f = first {
    if let s = second {
        println(f + s)
    }
} else {
    println("error")
}

このように、Optional Bindingだけでネストが深くなってしまうような状態でした。

しかし、Swift1.2からは

swift1.2
let first : Int? = "1".toInt()
let second : Int? = "2".toInt()

if let f = first, s = second {
    println(f + s)
} else {
    println("error")
}

と複数の変数を1度にOptional Bindingできるようになりました。

これでOptional Bindingでネストが深くなるという心配はなくなりましたね!

38
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
36