1
2

More than 5 years have passed since last update.

Swift制御構文まとめ

Last updated at Posted at 2018-08-05

条件分岐

if文

if a > 0 {

} else if a > 10 {

} else {

}
  • 条件に()をつける必要はない
  • {}は省略不可
  • 条件にbool型以外を入れることはできない

switch文

let n = 4
switch n {
case 0: print("nはゼロでした")
case 1: print("1や")
case 3: break
default:
    print("あーーーー!!!!")
}

switch n {
case 4:
    print(4)
    fallthrough
case 5:
    print(5)
default:
    print(1)
}
  • case毎にbreakを書く必要がない
    • breakを書かなくてもcase文が何か一致したらその時点で処理は終了
  • case文が一致した後も処理を続けたい場合は「fallthrough」を使う
    • fallthroughを使うと次のcase文は条件が一致してなくても実行される。
      • 上の例だと4と5がprintされる
  • caseのあとは必ず何か文を書かないといけない
    • 「case:」だとエラー, 「case: break」って書くことができる

三項演算子

let i = 3
let s = i == 1 ? "1や" : "1やない"
print(s)
  • 特に他の言語とかわらない雰囲気

繰り返し

while文

var i = 1 //変数定義

while i < 10 {
    print(i)
    i += 1
}

var j = 1

while j < 10 {
    if j % 3 == 0 {
        j += 1
        continue
    }
    print("\(j)は3の倍数ではない")
    j += 1
}

var k = 1

while k < 10 {
    if k % 3 == 0 {
        break
    }
    print("3の倍数がきたらwhile文が終わる")
    k += 1
}
  • 条件に()をつける必要はない
  • swift3で++, --は廃止されているので使えない
  • ループから抜け出す時にbreak, 繰り返しの内容を1つ飛ばす時にcontinueは使える

repeat-while文

var i = 4
repeat {
    print(i)
    i -= 1
} while i > 5
  • while文と一緒
  • 他の多くの言語でいうdo-while文と一緒

for-in文

for i in 1 ..< 10 {
    print(i)
}

for i in 1 ... 10 {
    print(i)
}

for i in 1 ... 10 where i % 3 == 0 {
    print(i)
}

let fruits = ["banana", "peach", "apple"]
for s in fruits {
    print(s)
}
  • for i = 1; i < 9; i++ みたいなfor文はswift3で消えた
  • 「..<」と「 ...」で範囲を表す
    • 1 ..< 10だと1以上10未満
    • 1 ... 10だと1以上10以下
  • whereをつけることで条件をつけることができる
    • where i % 3 == 0で3で割った余りが0(つまり3の倍数)の時だけ実行する
  • in の右側に配列を指定することができる
    • 配列を指定すると配列の中身を順番に取り出してくれる

foreach

let me = ["name": "da-ike", "age": "27", "address": "Cebu"]
me.forEach { (key, value) in
    print("\(key)は\(value)です")
}

let fruits = ["banana", "peach", "apple"]
fruits.forEach { (value) in
    print("\(value)です")
}
  • 特になし
1
2
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
1
2