LoginSignup
4
3

More than 5 years have passed since last update.

Swiftはじめたい...その7 if , switch

Posted at

今回はifとswitch文です。

ifは、わざわざ書く必要ないくらいふつーかも...

if
let a = true
// ふつーのif
if ( a ) {
    print(a)
}
// これもカッコがなくてもOK
if a {
    print(a)
}
  • forと同様でカッコがなくてもOKなことぐらいですね。

switch

  • これもふつーです。
switch
// 数値
let a = (0..<5)
for v in a {
    switch v {
    case 1:
        print("a")
    case 2:
        print("b")
    case 3:
        print("c")
    default:
        print("other")
    }
}

// 文字列
let b = ["z" , "a" , "b" , "c" , "d"]
for v in b {
    switch v {
    case "a":
        print("a")
    case "b":
        print("b")
    case "c":
        print("c")
    default:
        print("other")
    }
}

// 複数指定
let c = ["z" , "a" , "b" , "c" , "d"]
for v in c {
    switch v {
    case "a","c":
        print("a or c")
    case "b":
        print("b")
    default:
        print("other")
    }
}
  • 範囲指定できるのは便利かも!
範囲指定
// 範囲指定もできる
let d = (0..<100)
for v in d {
    switch v {
    case 1...10:
        print("1〜10")
    case 11...50:
        print("11〜50")
    case 51...100:
        print("51〜100")
    default:
        print("other")
    }
}

まとめ

  • そんな変な構文になるわけないですよね。
  • switchの範囲指定は便利かもしれません。

今日はここまで

  • 次回はなにを試そうか?宿題にしてたLazyMapCollectionか?正規表現か?文字列操作か?
4
3
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
4
3