一般陣列
var array = [(值)]
var array: [(型別)] = [(值)]
var array: Array<(型別)> = [(值)]
var array = ["a", "b", "c", "d"]
for i in array {
print("\(i) ", terminator: "")
}
print("\n\(array)")
range 範圍
var array = (數字)...(數字)
var array = 1...10
for i in array {
print("\(i) ", terminator: "")
}
輸出結果
1 2 3 4 5 6 7 8 9 10
stride 跨步
var array = stride(from: (起始值), through: (結束值), by: (間隔值))
var array = stride(from: (起始值), to: (結束值), by: (間隔值))
var array = stride(from: 10, through: 0, by: -2)
for i in array {
print("\(i) ", terminator: "")
}
print("")
var array2 = stride(from: 10, to: 0, by: -2)
for i in array2 {
print("\(i) ", terminator: "")
}
輸出結果
10 8 6 4 2 0
10 8 6 4 2
repeat 重複
var array = [(型別)](repeating: (值), count: (數量))
var data = [String](repeating: "a", count: 10)
for i in data {
print("\(i) ", terminator: "")
}
count 計數
let array = ["a", "b", "c", "d"]
print("\(array.count)")
append 插入尾端
var array = ["a", "b", "c", "d"]
array.append("e")
for i in array {
print("\(i) ", terminator: "")
}
insert 插入
var array = ["a", "b", "c", "d"]
array.insert("e", at: 2)
for i in array {
print("\(i) ", terminator: "")
}
remove 移除
var array = ["a", "b", "c", "d"]
array.remove(at: 1)
for i in array {
print("\(i)", terminator: "")
}
removeLast 移除尾端
var array = ["a", "b", "c", "d"]
array.removeLast()
for i in array {
print("\(i) ", terminator: "")
}
更換
var array = ["a", "b", "c", "d"]
array[1...2] = ["e", "f"]
for i in array {
print("\(i) ", terminator: "")
}
sorted 排序
let array = [100, 50, 70]
let bigtosmall = array.sorted(by: >)
for i in smalltobig {
print("\(i) ", terminator: "")
}
let smalltobig = array.sorted(by: <)
for i in bigtosmall {
print("\n\(i)", terminator: "")
}
isEmpty 空陣列
let array = ["a", "b", "c", "d"]
if array.isEmpty {
print("nothing")
}
else {
for i in array {
print("\(i) ", terminator: "")
}
}
宣告字典
var dictionary = [(key): (value)]
var dictionary: [(型別): (型別)] = [(key): (value)]
var dictionary: Dictionary<Int, String> = [(key): (value)]
var array = [1: "John", 2: "Harry", 3: "Kevin", 4: "Alex"]
for(i, j) in array {
print("\(i): \(j)", terminator: "")
}
讀取
var array: [Int: String] = [1: "John", 2: "Harry", 3: "Kevin", 4: "Alex"]
print("\(array.count)")
print("\(array[1])")
for i in array.keys {
print("\(i) ", terminator: "")
}
for i in array.values {
print("\(i) ", terminator: "")
}
for (i, j) in array {
print("number: \(i), name: \(j)")
}
輸出結果
4
Optional("John")
2 3 1 4 Harry Kevin John Alex
number: 2, name: Harry
number: 3, name: Kevin
number: 1, name: John
number: 4, name: Alex
更換
var array: [Int: String] = [1: "John", 2: "Harry", 3: "Kevin", 4: "Alex"]
array[1] = "Bob"
print("\(array[1])")
array[1] = nil
print("\(array[1])")
array.updateValue("GOOD", forKey: 1)
print("\(array[1])")
array[5] = "Potter"
print("\(array[5])")
array.removeValue(forKey: 5)
print("\(array[5])")