1. 程式人生 > >swift 3.0 再探索 - 2.Array & Dictionary

swift 3.0 再探索 - 2.Array & Dictionary

swift 3.0 再探索 - 2.Array & Dictionary

上一章講了Swift 3.0的String 和 String常用的API,這一篇講解一下 Array 和 Dictionary。
(這裡順便提一下Set–集合)
在swift中關於Array和Dictionary:

  • Array:有序可重複, 用於儲存同一型別的值. 最常用。
  • Dictionary:值無序可重複,但每個值有唯一的標記(Key)
  • Set:值無序不重複。

Array, Set和Dictionary在開發中,可以做為一種臨時存取的資料結構,在開發中很多時候都對這些基本型別進行操作,下面三種類型一起講解,相互對比一下:
- 建立

//不可變的,無法修改,改變

let constArray : [String]  = ["1", "2", "3", "4", "5", "2"]

let constDict : Dictionary<String, String> = ["1": "1", "2" : "2"]

let constSet : Set = ["1", "2", "3", "4", "5", "2"]

print(constArray)
print(constDict)
print(constSet)

//可變,可以修改值,長度,元素
var mutableArray : [String] = ["1"
, "2", "3", "4", "5", "2"] var mutableDict1 : Dictionary<String, String> = ["1":"1", "2":"2"] var mutableDict2 : [String : String] = ["3":"3" , "4":"4", "5":"5"] var mutableSet : Set<String> = ["1", "2", "3", "4", "5", "2"] print(mutableArray) print(mutableDict1) print(mutableDict2) print(mutableSet) //列印結果
let 宣告 ["1", "2", "3", "4", "5", "2"] ["1": "1", "2": "2"] ["1", "2", "3", "5", "4"] var 宣告 ["1", "2", "3", "4", "5", "2"] ["1": "1", "2": "2"] ["3": "3", "5": "5", "4": "4"] ["1", "2", "3", "5", "4"]
  • Array 的宣告: 變數/常量名 : [元素型別] = [元素, 元素, 元素, 元素, 元素]
    – 元素型別可以寫成<元素型別>, 或直接等於陣列結構。
  • Set 的宣告: 變數/常量名 : Set<元素型別> = [元素, 元素, 元素, 元素, 元素]
    – Set雖不能型別判斷,但是可以省略<元素型別>
  • Dictionary 的宣告: 變數/常量名 : Dictionary<鍵的型別,值的型別> = [鍵:值]
    – 或寫成:變數/常量名 : [鍵的型別 : 值的型別] = [鍵:值]
  • 特殊建立
//建立一個有預設值的陣列,加引數count和repeatedValue
let people = Array.init(repeating: "中國人", count: 12)
/*
    或寫成
    let people = [String](repeating: "中國人", count: 12)
    一個String型別陣列,有12個元素,這12個元素都是重複的"中國人"字串
 */
let person1 = people.first
print("有\(people.count)個\(person1!)")
//列印結果:"有12箇中國人\n"

//建立一個有序範圍的Int陣列,Array(起始值...終止值)
let oneToHundred = Array(1...100)
print(oneToHundred)

//列印結果:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

let和var的取值型別一致,下面接以var宣告作為講解例子。
- 取值

var mutableArray = ["1", "two", "3", "four", "5"]
var mutableSet : Set = ["北京", "上海", "廣州", "深圳", "天津"]
var mutableDict = ["Animal1":"Dog", "Animal2":"Cat", "Animal3":"Mouse"]

//判斷是否為空
let arrIsEmpty = mutableArray.isEmpty //Bool --> "false"
let setIsEmpty = mutableSet.isEmpty   //Bool --> "false"
let dictIsEmpty = mutableDict.isEmpty //Bool --> "false"

//Array 取值
let arrIndex1 = mutableArray.first //String? --> "1"
let arrIndex2 = mutableArray[mutableArray.index(after: 0)] //String? --> "two"
let arrIndex3 = mutableArray[2] //String? --> "3"
let arrIndex4 = mutableArray[mutableArray.index(before: 4)] //String? --> "four"
let arrIndex5 = mutableArray.last   //String? --> "5"

//Dictionary 取值
let value1 = mutableDict["Animal1"] //String? --> "Dog"
let keysArray = [String](mutableDict.keys) //["Animal1", "Animal3", "Animal2"]
let valuesArray = [String](mutableDict.values)//["Dog", "Mouse", "Cat"]
  • Set無序所以無法根據下標和Key去取值,控制語句時候講解如何遍歷Array, Set和Dictionary。
  • 增刪改:
var mutableArray = ["1", "two", "3", "four", "5"]
var mutableSet = ["北京", "上海", "廣州", "深圳", "天津"]
var mutableDict = ["Animal1":"Dog", "Animal2":"Cat", "Animal3":"Mouse"]

//陣列
let constArray = ["9999", "8888"]
//追加一個元素 --> ["1", "two", "3", "four", "5", "7777"]
/**
 *API:public mutating func append(_ newElement: Element)
 */
mutableArray.append("7777")

//追加一個數組裡面的元素 ["1", "two", "3", "four", "5", "7777", "9999", "8888"]
/**
 *API:+=< C, += C
 */
mutableArray += constArray

//插入元素"sssw",到index = 2的位置(下標從0開始算起)--> ["1", "two", "sssw", "3", "four", "5", "7777", "9999", "8888"]
/**
 *API:public mutating func insert(_ newElement: Element, at i: Int)
 */
mutableArray.insert("sssw", at: 2)

//刪除index = 3 的的元素,API將被刪除的元素 --> ["1", "sssw", "3", "four", "5", "7777", "9999", "8888"] , moveOject : "two"
/**
 *API:public mutating func remove(at index: Int) -> Element
 */
let moveOjbect = mutableArray.remove(at: 1)

//刪除第一個元素 -->["sssw", "3", "four", "5", "7777", "9999", "8888"]
/**
 *API:public mutating func removeFirst() -> Element
 */
mutableArray.removeFirst()

//刪除最後一個元素 --> ["sssw", "3", "four", "5", "7777", "9999"]
/**
 *API:public mutating func removeLast() -> Element
 */
mutableArray.removeLast()

//刪除所有元素 -->
/**
 *API:public mutating func removeAll(keepingCapacity keepCapacity: Bool = default)
 */
mutableArray.removeAll()

//其它API 陣列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var numberArray = Array(1...10)

//陣列中最大值 --> 10 (字串按照字元在Ascii碼中的排序, 如有中文按拼音首字母排序)
/**
 *API:public func max() -> Element?
 */
let max = numberArray.max()

//陣列中最小值 --> 1
/**
 *API:public func min() -> Element?
 */
let min = numberArray.min()

//一組數求和 --> 55
/**
 *API:public func reduce<T>(_ initial: T, combine: @noescape (T, Element) throws -> T) rethrows -> T 這是一個泛型的API
 */
let sum = numberArray.reduce(0, combine: +)

//求積 --> 3628800
/**
 *API:同上
 */
let product = numberArray.reduce(1, combine: *)

//字串按照按某一個字元切割成陣列 --> ["let", "us", "learn", "swift"]
/**
 *API:public func components(separatedBy: CharacterSet) -> [String]
 */
var str = "let us learn swift"
var words = str.components(separatedBy: " ")

//數字按照某一個字元拼接成字串 --> letuslearnswift
/**
 *API:public func joined(separator: CharacterSet) -> String
 */
str = words.joined(separator: "")

//Set
//增加元素
//無條件地將給定的元素"長沙"插入到集合中
/**
 *API:public mutating func update(with newMember: Element) -> Element?
 */
mutableSet.update(with: "長沙")

//插入一個"武漢" --> ["北京", "上海", "武漢", "廣州", "深圳", "天津", "鄭州", "長沙"]
/**
 *API:public mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element)
 */
mutableSet.insert("武漢")

//刪除元素
//根據下標刪除 --> 返回被刪除的元素"北京" , 剩下的元素是["武漢", "長沙", "鄭州", "上海", "廣州", "深圳", "天津"]
/**
 *API:public mutating func remove(_ member: Element) -> Element?
 */
mutableSet.remove("北京")

//根據SetIndex刪除 --> ["武漢", "長沙", "上海", "廣州", "深圳", "天津"]
/**
 *API:public mutating func remove(at position: SetIndex<Element>) -> Element
 */
let setIndex = mutableSet.index(mutableSet.startIndex , offsetBy: 2)
mutableSet.remove(at: setIndex)

//包含,交差並補
//判斷是否包含某個元素 --> true
/**
 *API:public func contains(_ member: Element) -> Bool
 */
let result = mutableSet.contains("長沙")

//轉排序,升序 --> [1, 2, 3, 4, 8, 9, 10]
/**
 *API:public func sorted() -> [Element]
 */
var numberSet : Set = [1, 3, 4, 2, 10, 9, 8]
let setToArray = numberSet.sorted()

//交集 intersect
//當前的mutableSet = ["深圳", "天津", "鄭州", "長沙"]
/**
 *API:public mutating func formIntersection<S : Sequence where S.Iterator.Element == Element>(_ other: S)
 刪除不相同的元素 --> ["廣州", "深圳"]
 */
let neighbors = ["北京", "上海", "廣州", "深圳"]
mutableSet.formIntersection(neighbors)

//差集 subtract
//當前的mutableSet = ["廣州", "深圳"]
/**
 *API:public mutating func subtract<S : Sequence where S.Iterator.Element == Element>(_ other: S)
 刪除相同的元素 --> ["廣州", "深圳"]
 */
mutableSet.subtract(neighbors)

//並集 union
//當前的mutableSet = []
/**
 *API:public func union<S : Sequence where S.Iterator.Element == Element>(_ other: S) -> Set<Element>
 返回兩者都有的元素 -->["廣州", "北京", "上海", "深圳"]
 */
let new = mutableSet.union(neighbors)

//補集 exclusive
//當前的mutableSet = []
/**
 *API:public func symmetricDifference<S : Sequence where S.Iterator.Element == Element>(_ other: S) -> Set<Element>
 返回一個新的集合,並且原集合是否存在這些元素 -->["廣州", "北京", "上海", "深圳"]
 */
let new1 = mutableSet.symmetricDifference(neighbors)

//其它用法
let set1 : Set = [1,2,3,4,5]
let set2 : Set = [4,5,6,7,8]
let set3 : Set = [1,2,3,4,5,4,5,6,7,8]
let set4 : Set = [5,2,3,4,1]
let set5 : Set = [10,11,12]

//子集: isSubsetOf(可以相等), 嚴格子集isStrictSubsetOf
/**
 *API: 1.public func isSubset(of other: Set<Element>) -> Bool
       2.public func isStrictSubset(of other: Set<Element>) -> Bool
 描述:  1.返回一個Bool判斷是否是子集
        2.返回一個Bool判斷是否是真子集
 */
let result1 = set1.isSubset(of: set4)
let result2 = set1.isStrictSubset(of: set3)

//父集: isSupersetOf(可以相等), 嚴格父集isStrictSuperSetOf
/**
 *API: 1.public func isSuperset(of other: Set<Element>) -> Bool
       2.public func isStrictSuperset(of other: Set<Element>) -> Bool
 描述:  1.返回一個Bool判斷是否是父集
        2.返回一個Bool判斷是否是真父集
 */
let result3 = set1.isSuperset(of: set4)
let result4 = set3.isStrictSuperset(of: set1)

//無交集: isDisjointWith
/**
 *API:public func isDisjoint(with other: Set<Element>) -> Bool
      是否存在交集
 */
set1.isDisjoint(with: set5)
set1.isDisjoint(with: set2)

//dictionary 增加鍵值對
//增加 Animal4 : Monkey
/**
 *API: public mutating func updateValue(_ value: Value, forKey key: Key) -> Value?
    用於更新Dictionary中的鍵值對,如果存在相同的鍵,則更新鍵對應的值,返回被更新的值;反之,插入新的鍵值對,返回值為nil
    ["Animal3": "Mouse", "Animal1": "Dog", "Animal4": "Monkey", "Animal2": "Cat"]
 */

let value = mutableDict.updateValue("Monkey", forKey: "Animal4")


//刪除鍵值對
/**
 *API: public mutating func removeValue(forKey key: Key) -> Value?
    根據鍵去刪除,相對應的鍵值對,返回被刪除的值
    ["Animal4": "Monkey", "Animal2": "Cat", "Animal3": "Mouse"]
 */

let result = mutableDict.removeValue(forKey: "Animal1")

/**
 *API: public mutating func removeAll(keepCapacity keepCapacity: Bool = default)
    刪除所有的鍵值對,無返回值。
 */

mutableDict.removeAll()


  • 總結

  • Array和Dictionary可以改變其的內容,對資料進行臨時的持有。
    下一篇講解一下,常規開發中,特殊的String,Array, Dictionary與其它型別的轉換。