プログラミング言語Swiftの基本の続きを解説します。
コレクション型
Swiftには、データのコレクションを格納するための3つの主要なコレクション型があり、それは配列(Array)、辞書(Dictionary)、セット(Set)となります。
配列(Array)
配列は、同じ型の値を順序付きで格納するコレクションです。
var shoppingList: [String] = ["Eggs", "apple"]
shoppingList.append("Bread")
print(shoppingList) // ["Eggs", "apple", "Bread"]
辞書(Dictionary)
辞書は、キーと値のペアを格納するコレクションです。
各キーはユニークで、値は重複しても構いません。
var occupations: [String: String] = ["Malcolm": "Captain", "Kaylee": "Mechanic"]
occupations["Jayne"] = "Public Relations"
print(occupations) // ["Malcolm": "Captain", "Kaylee": "Mechanic", "Jayne": "Public Relations"]
セット(Set)
セットは、ユニークな値を無順序で格納するコレクションです。
var favoriteGenres: Set<String> = ["Rock", "Classical", "Techno"]
favoriteGenres.insert("Jazz")
print(favoriteGenres) // 無順序で表示される
制御フロー
Swiftには、コードの流れを制御するための構造がいくつかあり、if
文、guard
文、switch
文、ループ(for-in
ループ、while
ループ、repeat-while
ループ)があります。
if文
let score = 85
if score >= 90 {
print("Grade: A")
} else if score >= 81 {
print("Grade: B")
} else {
print("Grade: C")
}
guard文
guard
文は、条件が満たされない場合にスコープ外に退出を行うために使用されます。
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello, \(name)!")
}
switch文
switch
文は、複数の条件に基づいてコードの実行を分岐させるために使用されます。
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
for-in ループ
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
while ループ
var n = 2
while n < 100 {
n *= 2
}
print(n) // 128
repeat-while ループ
var m = 2
repeat {
m *= 2
} while m < 100
print(m) // 128