LoginSignup
29
28

More than 5 years have passed since last update.

Swift2のOptional Pattern

Last updated at Posted at 2015-06-10

Swift2で新しく下記のような書き方ができるようになりました。

let someOptional: Int? = 42

// enumeration case pattern
if case .Some(let x) = someOptional {
    print(x)
}

// optional pattern (結果は上のenumeration case patternと同じ)
if case let x? = someOptional {
    print(x)
}

これは下記のシンタックスシュガーとのこと。

let someOptional: Int? = 42

switch (someOptional) {
case .Some(let x):
    print(x)
default:
    break
}

メリット

1行でパターンマッチができるようになります。

let abc = (1, 2, 3)

if case (1, let y, let z) = abc {
    print("\(y), \(z)")
}

forでも使用できます。

let profiles = [("Frodo", 50), ("Aragorn", 78), ("Legolas", 2931), ("Boromir", 40)]

for case let (name, 0...100) in profiles {
    print("\(name) is young.")
}

guardでも使用できます。

let someOptional: Int? = 42

guard case let x? = someOptional where x > 100 {
    return
}

print(x)

ついでに複数まとめて書くこともできます。(ifでも可)

let someOptional: Int? = 42
let something: String? = "Hello World"

guard case let x? = someOptional where x > 100,
      case let str? = someThing where str.hasPrefix("Hello") else {
    return
}

print("\(x) : \(str)")

便利そうですね。

29
28
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
29
28