swift 3.0 再探索 - 2.Array & Dictionary

来源:互联网 发布:快速除法的算法实现 编辑:程序博客网 时间:2024/06/08 20:08

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和repeatedValuelet people = Array.init(repeating: "中国人", count: 12)/*    或写成    let people = [String](repeating: "中国人", count: 12)    一个String类型数组,有12个元素,这12个元素都是重复的"中国人"字符串 */let person1 = people.firstprint("有\(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与其它类型的转换。
0 0
原创粉丝点击