ch03字符串和字符
swift提供三种基本的集合类型,arrays,sets,dictionaries,来存储值的集合,arrays是有序的集合,sets和dictionaries是无序的集合,
//如果你在创建arrays,sets,dictionaries的时候,将它分配给变量,那么集合将是可变的,也就是说你可以添加,删除,或者改变集合中items,如果将它分配给常量,那么集合将是不可变的
//数组是存储相同类型的有序列表,相同类型的值可以出现在数组中的不同位置, //数组类型语法速记 //创建空的数组 var someInts = [Int]() //print("someInts is of type [Int] with \(someInts.count) items") // prints "someInts is of type [Int] with 0 items." //说明someInts变量的类型被推断为[Int]类型 //另外,如果内容已经提供了类型信息,比如作为函数参数或者是已经存在的一个变量或者常量的类型,你可以用这个数组名字创建一个空的数组, someInts.append(3) // someInts now contains 1 value of type Int someInts = [] // someInts is now an empty array, but is still of type [Int] //创建带默认值的数组 //swift的array提供了一种初始化方法,来创建一个长度有限,所有值都是相同默认值的数组 var threeDoubles = [Double](count: 3, repeatedValue: 0.0) // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0] //通过将两个数组拼在一起,来创建一个新的数组 //你可以创建一个新的数组,通过操作符+将两个数组拼在一起,新的数组类型将根据这两个拼接的数组的类型来判断 var anotherThreeDoubles = [Double](count: 3, repeatedValue: 2.5) // anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5] var sixDoubles = threeDoubles + anotherThreeDoubles //print(sixDoubles) // sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5] //通过数组文本创建新的数组 //数组文本的格式如下: //[<#value1#>,<#value2#>,<#value3#>] //下面的例子创建一个shoppingList数组来存储String值 var shoppingList: [String] = ["Eggs","Milk"] // shoppingList has been initialized with two initial items //shoppingList变量被声明为一个数组,用来存储字符串类型的值,[String]; //说明:shoppingList数组被声明为变量(var),不是常量(let),因此更多的items可以被加到数组中 //由于swift的类型推断,你没必要写一个数组的类型,如果你在初始化的时候,数组文本包含相同类型的值,正如var shoppingList: [String] = ["Eggs","Milk"],由于数组文本的值都是String类型,所以swift推断shoppingList的类型为[String] //访问和修改数组 //你可以通过数组的方法和属性或者标语法来访问和修改数组 //通过数组的只读属性count,来获取数组中items的个数 //print("The shopping list contains \(shoppingList.count) items.") // prints "The shopping list contains 2 items." //通过数组的isEmpty属性来判断count属性是否等于0 //if shoppingList.isEmpty { // print("The shopping list is empty.") //} else { // print("The shopping list is not empty.") //} // prints "The shopping list is not empty." //通过调用数组的 append(_:)方法,来添加一个新的item到数组的最后 shoppingList.append("Flour") // shoppingList now contains 3 items, //通过操作符+=,来添加多个items shoppingList += ["Baking Powder"] // shoppingList now contains 4 items shoppingList += ["Chocolate Spread", "Cheese", "Butter"] // shoppingList now contains 7 items //通过标语法来检索数组的值 var firstItem = shoppingList[0] // firstItem is equal to "Eggs" //你可以通过标语法来改变已经存在的值 shoppingList[0] = "Six eggs" // the first item in the list is now equal to "Six eggs" rather than "Eggs" //你也可以通过标语法来改变多个值 shoppingList[4...6] = ["Bananas", "Apples"] //print(shoppingList.count) // shoppingList now contains 6 items //说明:你不能通过标语法来添加一个新的item在数组的结尾 //调用数组insert(_:atIndex:)方法,来插入一个值 shoppingList.insert("Maple Syrup", atIndex: 0) //print(shoppingList.count) // shoppingList now contains 7 items //print(shoppingList) // "Maple Syrup" is now the first item in the list //类似的,调用removeAtIndex(_:)方法来移除一个item,这个方法移除特定位置的item,并且返回这个被移除的item,(如果没必要,你可以忽略这个返回值) let mapleSyrup = shoppingList.removeAtIndex(0) //print(mapleSyrup) // the item that was at index 0 has just been removed // shoppingList now contains 6 items, and no Maple Syrup // the mapleSyrup constant is now equal to the removed "Maple Syrup" string firstItem = shoppingList[0] //print(firstItem) // firstItem is now equal to "Six eggs" //如果你想移除数组的最后一个item,使用removeLast()方法,而不是removeAtIndex(_:) let apples = shoppingList.removeLast() //print(apples) // the last item in the array has just been removed // shoppingList now contains 5 items, and no apples // the apples constant is now equal to the removed "Apples" string //迭代数组 for item in shoppingList { // print(item) } // Six eggs // Milk // Flour // Baking Powder // Bananas //调用数组的enumerate()方法,你可以获得每一个item的索引,enumerate()方法返回由索引组成的元组,你可以分解这个元组为暂时的常量或者变量 for (index,value) in shoppingList.enumerate() { // print("Item \(index+1): \(value)") } // Item 1: Six eggs // Item 2: Milk // Item 3: Flour // Item 4: Baking Powder // Item 5: Bananas
//集合存储相同类型的不同值,集合是无序的, //哈希值集合类型--Hash Values for Set Types //哈希值是Int类型值,所有相同的对象值可以比较大小,比如:如果 a == b,也可以是这样:a.hashValue == b.hashValue //swift所有的基本类型(String,Int,Double,Bool)默认都是哈希值 //集合类型的语法,集合类型被写成这样:Set<Element>,Element是类型 //创建一个空的集合 var letters = Set<Character>() //print("letters is of type Set<Character> with \(letters.count) items") // prints "letters is of type Set<Character> with 0 items." letters.insert("a") // letters now contains 1 value of type Character letters = [] // letters is now an empty set, but is still of type Set<Character> //通过数组文本创建集合 //var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] // favoriteGenres has been initialized with three initial items //集合的类型不能单独根据数组文本推断出,因此集合类型一定要被准确声明,但是因为swift的类型推断,如果你初始化数组文本为相同的类型,你没必要写集合的类型,因此上面的定义可以写成这样: var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"] //访问和修改集合 //获取集合中item的个数 //print("I have \(favoriteGenres.count) favorite music genres.") // prints "I have 3 favorite music genres." //判断集合是否为空 //if favoriteGenres.isEmpty { // print("As far as music goes, I'm not picky.") //} else { // print("I have particular music preferences.") //} // prints "I have particular music preferences." //添加新的item favoriteGenres.insert("Jazz") // favoriteGenres now contains 4 items //移除items //调用集合的remove(_:)方法来移除item,如果items是集合的成员,那么返回这个移除的值,如果集合没有这个item,那么返回nil;另外你也可以移除所有的item,通过调用removeAll()方法 //if let removedGenre = favoriteGenres.remove("Rock") { // print("\(removedGenre)? I'm over it.") //} else { // print("I never much cared for that.") //} // prints "Rock? I'm over it." //判断某个item是否存在 //if favoriteGenres.contains("Funk") { // print("I get up on the good foot.") //} else { // print("It's too funky in here.") //} // prints "It's too funky in here." //迭代集合 for genre in favoriteGenres { // print("\(genre)") } //Rock //Classical //Jazz //Hip hop //swift的集合类型是无序的,为了按特定顺序迭代,使用sort()方法 for genre in favoriteGenres.sort() { // print("\(genre)") } //Classical //Hip hop //Jazz //Rock
//基本的集合运算 //集合a和集合b //取交集,调用集合的intersect(_:)方法: //调用集合的exclusiveOr(_:)方法,创建一个新的集合,这个集合中item不属于a和b的交集 //取并集,调用集合的union(_:)方法: //调用集合的subtract(_:)方法,创建一个新的集合,这个集合中item属于集合a,但是不属于集合b let oddDigits: Set = [1,3,5,7,9] let evenDigits: Set = [0,2,4,6,8] let singleDigitPrimeNumbers: Set = [2,3,5,7] //print(oddDigits.union(evenDigits).sort()) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] //print(oddDigits.intersect(evenDigits).sort()) // [] //print(oddDigits.subtract(singleDigitPrimeNumbers).sort()) // [1, 9] //print(oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()) // [1, 2, 9] //集合的成员和相等 //定义三个集合:a,b,c,其中集合a是集合b的父类集合,因为a中有b中所有的items //相等:==判断两个集合是不是含有所有相同的值 //子集合:isSubsetOf(_:) //父集合:isSupersetOf(_:) //交集:isDisjointWith(_:) //isStrictSubsetOf(_:) or isStrictSupersetOf(_:)方法来确定一个集合是否是另一个集合的子集合或者父集合,但是有不等于某个特定的集合 let houseAnimals: Set = ["",""] let farmAnimals: Set = ["","","", "", ""] let cityAnimals: Set = ["", ""] //print(houseAnimals.isSubsetOf(farmAnimals)) //true //print(farmAnimals.isSupersetOf(houseAnimals)) //true //print(farmAnimals.isDisjointWith(cityAnimals))//没有交集返回true //true
//字典是无序的, //字典的语法,字典类型被写成:Dictionary<key,Value>,也可以写成这样:[key:Value] //创建空的字典 var namesOfIntegers = [Int: String]() // namesOfIntegers is an empty [Int: String] dictionary namesOfIntegers[16] = "sixteen" // namesOfIntegers now contains 1 key-value pair namesOfIntegers = [:] // namesOfIntegers is once again an empty dictionary of type [Int: String] //通过字典文本来创建字典 //[key 1: value 1, key 2: value 2, key 3: value 3] //var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] //正如数组那样,如果你初始化一个字典文本,他的键值对有着连续的类型,那么你没必要写字典的类型为,上面的变量声明可以写成下面的样子, var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] //访问和修改字典 //获取字典的长度 //print("The airports dictionary contains \(airports.count) items.") // prints "The airports dictionary contains 2 items." //判断字典是否为空 //if airports.isEmpty { // print("The airports dictionary is empty.") //} else { // print("The airports dictionary is not empty.") //} // prints "The airports dictionary is not empty." //通过标语法来添加新的键值对 airports["LHR"] = "London" // the airports dictionary now contains 3 items //通过标语法修改已有的键值对 airports["LHR"] = "London Heathrow" // the value for "LHR" has been changed to "London Heathrow" //使用字典的updateValue(_:forKey:)方法来设置和更新特定key的值,如果key不存在,那么updateValue(_:forKey:)方法会创建一个key,如果key值存在,那么updateValue(_:forKey:)会更新对应value,在执行更新后,updateValue(_:forKey:)方法返回旧的value,这样可以使你判断是否执行了更新 //比如,字典存放了String类型的值,updateValue(_:forKey:)方法会返回String?类型的值,这个可选的值含盖旧的值如果在更新之前存在,或者nil如果值不存在 if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") { // print("The old value for DUB was \(oldValue).") } // prints "The old value for DUB was Dublin." //if let airportName = airports["DUB"] { // print("The name of the airport is \(airportName).") //} else { // print("That airport is not in the airports dictionary.") //} // prints "The name of the airport is Dublin Airport." airports["APL"] = "Apple International" // "Apple International" is not the real airport for APL, so delete it airports["APL"] = nil // APL has now been removed from the dictionary //另外,调用字典removeValueForKey(_:)方法来移除键值对,如果键值对存在,返回被移除的值,如果键值对不存在,返回nil //if let removedValue = airports.removeValueForKey("DUB") { // print("The removed airport's name is \(removedValue).") //} else { // print("The airports dictionary does not contain a value for DUB.") //} // prints "The removed airport's name is Dublin Airport." //迭代字典 for (airportCode, airportName) in airports { // print("\(airportCode): \(airportName)") } //YYZ: Toronto Pearson //DUB: Dublin Airport //LHR: London Heathrow for airportCode in airports.keys { // print("Airport code: \(airportCode)") } //Airport code: YYZ //Airport code: DUB //Airport code: LHR for airportName in airports.values { // print("Airport name: \(airportName)") } //Airport name: Toronto Pearson //Airport name: Dublin Airport //Airport name: London Heathrow //使用字典的keys或者values创建新的数组 let airportCodes = [String](airports.keys) //print(airportCodes) //["YYZ", "DUB", "LHR"] let airportNames = [String](airports.values) //print(airportNames) //["Toronto Pearson", "Dublin Airport", "London Heathrow"] //字典是无序的,如果已特定到顺心迭代字典,在字典的keys or values属性用sort()方法 for airportCode in airports.keys.sort() { // print("Airport code: \(airportCode)") } //Airport code: DUB //Airport code: LHR //Airport code: YYZ