LoginSignup
85
75

More than 5 years have passed since last update.

Swift 2のfor-inフィルタとパターンマッチ (for-in-whereとfor-case-let-in)

Last updated at Posted at 2015-08-17

Swift 2.0では、ループ処理のfor-in文にフィルタとパターンマッチを適用できるようになります。WWDC 2015のビデオ "What's New in Swift" の19:20あたりから説明を見ることができます。

フィルタ (for-in-where)

Swift 1.x

    for value in 0..<10 {
        if value < 2 {
            println(value)
        }
    }

    // Prints:
    // "0"
    // "1"

Swift 2.0

    for value in 0..<10 where value < 2 {
        print(value)
    }

    // Prints:
    // "0"
    // "1"

パターンマッチ (for-case-let-in)

列挙型

Swift 1.x

    enum Exam {
        case Pass(Int)
        case Fail(Int)
    }

    let exams: [Exam] = [.Fail(40), .Pass(100), .Pass(80)]

    for exam in exams {
        switch exam {
        case .Pass(let score):
            println(score)
        default:
            break
        }
    }

    // Prints:
    // "100"
    // "80"

Swift 2.0

    for case .Pass(let score) in exams {
        print(score)
    }

    // Prints:
    // "100"
    // "80"

タプル

Swift 1.x

    let prices = [("Mocha", 430), ("Latte", 370), ("Cappuccino", 370), ("Americano", 340)]

    for (name, price) in prices {
        if price == 370 {
            println(name)
        }
    }

    // Prints:
    // "Latte"
    // "Cappuccino"

Swift 2.0

    for case let (name, 370) in prices {
        print(name)
    }

    // Prints:
    // "Latte"
    // "Cappuccino"

フィルタとパターンマッチの組み合わせ (for-case-let-in-where)

Swift 1.x

    for (name, price) in prices {
        if price == 370 {
            if name.hasPrefix("L") {
                println(name)
            }
        }
    }

    // Prints: "Latte"

Swift 2.0

    for case (let name, 370) in prices where name.hasPrefix("L") {
        print(name)
    }

    // Prints: "Latte"

まとめ

for-inでフィルタやパターンマッチを利用することにより、if文の入れ子を減らすことができます。filter, map, flatMap, reduceと比較し、わかりやすく書ける方を採用すればいいでしょう。

85
75
1

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
85
75