[swift] for in構文まとめ

for in構文まとめ

//回数指定ループ

for i in 0 ... 5 {
    print("i \(i)")
}
//結果
//i 0
//i 1
//i 2
//i 3
//i 4

for i in 10 ... 5 {
    print("i \(i)")
}
//結果
//i 10
//i 11
//i 12
//i 13
//i 14

配列から要素取り出しループ

let arr = ["apple","google","facebook","amazon"]
for i in arr {
    print("i \(i)")
}

//結果
//i apple
//i google
//i facebook
//i amazon

配列から要素取り出しループ(回数指定)

let arr = ["apple","google","facebook","amazon"]
for i in 0...3 {
    print("i \(arr[i])")
}

//結果
//i apple
//i google
//i facebook

辞書型から要素取り出しループ

let tests = ["Eng": 80, "Science": 60, "Math": 70]
for (courseTitle, score) in tests {
    print("\(courseTitle) : \(score)")
}

//結果
//Math : 70
//Science : 60
//Eng : 80

Stringをベースにてループ回数指定

var str = "hello"
for s in str{
    print("s \(s)")
}
//結果
//s h
//s e
//s l
//s l
//s o

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です