LoginSignup
46

More than 3 years have passed since last update.

Swiftのif文でwhereを使ったときのelseの条件

Last updated at Posted at 2015-05-13

※ Swiftバージョン1.2の頃の話なのでコメント欄もご参照ください:bow:

Whereを使ったときのelseの条件

Swift1.2からif文でwhereが使えるようになりました。
これによってネストせずにOptionalな変数をアンラップしてから中身を判定することができます。
ただ、その場合にelse句はアンラップして中身がなかった場合なのか、whereの判定がfalseになったからなのか疑問だったので調べてみました。

func test(token: String?) {
    if let t = token where t.isEmpty {
        println("token is empty")
    } else {
        println("token is nil or not empty")
    }
}

// 結果
test("")    // -> token is empty
test("xxx") // -> token is nil or not empty
test(nil)   // -> token is nil or not empty

結果は、アンラップして中身がなかった場合とwhereの判定がfalseになった場合どちらもelseに入りました。(当たり前か)

全部場合分けするには

全て場合分けしたい場合は以下のように書けますが余計分かりにくい。。

func test(token: String?) {
    if let t = token where t.isEmpty {
        println("token is empty")
    } else if token == nil {
        println("token is nil")
    } else {
        println("token is not empty")
    }
}

素直に入れ子にしたほうがよさそうです。

func test(token: String?) {
    if let t = token {
        if t.isEmpty {
            println("token is empty")
        } else {
            println("token is not empty")
        }
    } else {
        println("token is nil")
    }
}

switch文でやる(追記)

@Ushio@github さんからコメントで教えていただきました。
Switch文できれいに場合分けできてこれが一番見やすいですね!

func test(token: String?) {
    switch token {
    case let .Some(value) where value.isEmpty:
        println("token is Empty")
    case let .Some(value):
        println("token is Not Empty")
    case .None:
        println("token is nil")
    }
}

test("")
test("token")
test(nil)

/*
token is Empty
token is Not Empty
token is nil
*/

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
46