陣列 (Array)
有序的容器,可以包含相同的值
var numbers : [Int] = [1, 2, 3, 4]
//取值
print(numbers[0])
print(numbers[2])
陣列的基本操作
說明 | 範例 |
---|---|
append() | 新增元素 |
remove(at:) | 移除元素 |
removeAll() | 移除所有元素 |
insert(,at:) | 插入元素 |
sort(by:) | 排序 |
shuffle() | 洗亂順序 |
forEach() | 反覆依序取出元素 |
contains() | 找出包含有關的元素 |
first(where:) | 找出第一個符合條件的元素 |
joined(separator:) | 將陣列的所有元素以分隔符號串起為字串 |
swapAt() | 交換元素的位置 |
reversed() | 反序排列 |
count | 陣列長度 |
isEmpty | 陣列是否為空 |
randomElement() | 隨機給一個元素 |
值的修改就在該位置做賦值,就會蓋過去了
numbers[2] = 5
陣列的迴圈
for i in numbers {
print(i)
}
集合 Sets
無序的容器,所存放的值必須不同
var numberSet : Set = [112, 114, 115, 116, 117]
集合的基本操作
說明 | 範例 |
---|---|
contains() | 找出包含有關的元素 |
insert(,at:) | 插入元素 |
first(where:) | 找出第一個符合條件的元素 |
joined(separator:) | 將組合的所有元素以分隔符號串起為字串 |
remove(at:) | 移除元素 |
forEach() | 反覆依序取出元素 |
sort() | 排序 |
reversed() | 反序排列 |
count | 陣列長度 |
isEmpty | 陣列是否為空 |
randomElement() | 隨機給一個元素 |
集合的迴圈
for s in numbersSet {
print(s)
}
集合的特殊操作
假設兩個集合為已知
// first set
let setA: Set = [1, 2, 3]
// second set
let setB: Set = [2, 3, 4]
聯集 (Union)
print("Union: ", setA.union(setB))
交集 (Intersection)
print("Intersection: ", setA.intersection(setB))
差集 (Difference)
print("Subtracting: ", setA.subtracting(setB))
對稱差集 (Symmetric Difference )
print("Symmetric Difference: ", setA.symmetricDifference(setB))
檢查子集合 (isSubset)
print("isSubset: ", setA.isSubset(of:setB))
檢查相等 (equal)
print("is Equal: ", setA == setB)
字典 Dictionary
存儲資料是以 key - value 的型式存在
範例:
var telCode = ["Taiwan":"+886","US":"+1"]
字典的基本操作
增加元素(修改元素)
telCode["Japan"] = "+81"
取得所有的 keys
var countryName = Array(telCode.keys)
取得所有的 value
var values = Array(telCode.values)
用 key 來移除資料
telCode.removeValue(forKey: "US")
其他的基本操作
說明 | 範例 |
---|---|
count | 字典長度 |
first(where:) | 找出第一個符合條件的元素 |
isEmpty | 陣列是否為空 |
contains() | 找出包含有關的元素 |
remove(at:) | 移除元素 |
forEach() | 反覆依序取出元素 |
sort() | 排序 |
reversed() | 反序排列 |
randomElement() | 隨機給一個元素 |
shuffle() | 洗亂順序 |
元組(tuple)
//一個簡單的元組
var productTuple = ("MacBook", 1099.99)
print(productTuple.0)
print(productTuple.1)
//有名字的元組
var productTuple = (name: "MacBook", price: 1399.99)
print(productTuple.name)
print(productTuple.price)
//巢狀元組
var alphabets = ("A", "B", "C", ("a", "b", "c"))
//第 0 個 // 印出 "A"
print(alphabets.0)
//第 3 個 // 印出 ("a", "b", "c")
print(alphabets.3)
//第 3 個元組的第 1 個
print(alphabets.3.0) // 印出 "a"
轉載請註明來源,歡迎對文章中的引用來源進行考證,歡迎指出任何有錯誤或不夠清晰的表達。可以郵件至 [email protected]