引き続き制御構文です。
現場で案件が消えてしまったのでswift関連は書き出したけど止まりそうです😢(笑)
ゴリゴリのNative開発やりたかったなぁ。。
for in
for in は配列をループさせて、ひとつづ取り出します。
let smart_phones = ["iphone", "xpedia", "pixcel", "huawei"]
for smart_phone in smart_phones {
print("phone is : (smart_phone)")
}
/*--結果
phone is : iphone
phone is : xpedia
phone is : pixcel
phone is : huawei
--*/
dictionaryの時もひとつづ取り出します。
key / value でそれぞれにアクセスして値を取り出せます。
let apple_products = [0 : "iphone", 1: "macbook", 2: "apple watch", 3: "macbook pro"]
for apple_product in apple_products {
print("apple_product is : (apple_product)")
print("apple_product key is : (apple_product.key)")
print("apple_product value is : (apple_product.value)")
}
/*--結果
apple_product is : (key: 1, value: "macbook")
apple_product key is : 1
apple_product value is : macbook
apple_product is : (key: 3, value: "macbook pro")
apple_product key is : 3
apple_product value is : macbook pro
apple_product is : (key: 0, value: "iphone")
apple_product key is : 0
apple_product value is : iphone
apple_product is : (key: 2, value: "apple watch")
apple_product key is : 2
apple_product value is : apple watch
--*/
while
whileループです。
i++ とはかけないようです。
var i = 0
while i < 5 {
print("index is :(i)")
i += 1
}
/*-- 結果
index is :0
index is :1
index is :2
index is :3
index is :4
--*/
repeat while
repeat whileは最低1回は処理が行われます。
i = 0
repeat {
print("index is :(i)")
i += 1
} while i < 5
/*-- 結果
index is :0
index is :1
index is :2
index is :3
index is :4
--*/
if
if文は中括弧「()」ありでも、なしでも書けます。
ないほうがswiftらしい感じですね。
if i == 5 {
print("i is : 5")
} else if i == 4 {
print("i is : 4")
} else {
print("not 5 or 4")
}
/*-- 結果
i is : 5
--*/
絵文字なども扱えます。
let sushi:String = "🍣"
if (sushi == "🍣") {
print("寿司")
}
/*-- 結果
寿司
--*/
if の後に定数に入れるようにしてあげると、
値(value)が空でない場合のみtrueになります。
let value:Any? = 1000
if let result: Any = value {
print("(result)")
}
/*-- 結果
1000
--*/
switch
switch文はこんな感じです。
カンマで複数の値を指定できます。
i = 3
switch i {
case 1:
break
case 2, 3, 4:
print("i は 2 or 3 or 4")
break
case 5:
print("i はやっぱり 5")
break
default:
break
}
/*-- 結果
i は 2 or 3 or 4
--*/
範囲指定でも判定することができます。
switch i {
case 1...2:
print("1...2")
break
case 3..<10:
print("3..<10")
break
case 20..<100:
print("20..<100")
break
default:
break
}
/*-- 結果
3..<10
--*/
コメント