字符串操作
创建字符串常量
let someString = "Some string literal value"
初始化空字符串
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer Syntax
//判断字符串是否为空
if emptyString.isEmpty {
println("Nothing to see here")
}
遍历字符串(按字符遍历)
for character in "Dog!" {
if character == "g"{
print("\(character)")
}
}
String类型的值可以通过字符数组来进行构造初始化
let catCharacters: [Character] = ["C","a","t","!"]
let catString = String(catCharacters)
println(catString)
// prints "Cat!"
字符串拼接
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
//welcome.append("s")
获取字符串的字符数
let unusualMenagerie = "Koala,Snail,Penguin,Dromedary"
let count = count(unusualMenagerie)
var word = "cafe"
println("the number of characters in \(word) is \(count(word))")
// prints "the number of characters in cafe is 4"
字符串索引(索引从0开始)
let greeting = "Guten Tag"
println(greeting.startIndex)
// 0
println(greeting.endIndex)
// 9
greeting[greeting.startIndex]
// G
greeting[greeting.startIndex.successor()]//successor()当前索引+1
// u
greeting[greeting.endIndex.predecessor()]//predecessor()当前索引-1
// g
字符串插入
//插入字符
var wel = "Hello"
wel.insert("!",atIndex: wel.endIndex)
println(wel)
//插入字符串
wel.splice(" EveryBody",atIndex: wel.endIndex.predecessor())
println(wel)
字符串删除
//删除字符
wel.removeAtIndex(wel.endIndex.predecessor())
println(wel)
字符串比较
let quotation = "1.1We're a lot alike,you and I."
let sameQuotation = "1.2We're a lot alike,you and I."
if quotation == sameQuotation {
println("These two strings are considered equal")
}
集合操作
Swift提供三种主要的集合类型:array,set,dictionary
其存储的值的类型是明确的
Array数组
数组在一个有序链表里存储了多个类型相同的值。同一个值可以在数组的不同位置出现多次。
创建和初始化一个Array:
var someInts = [Int]();
println("someInts is of type [Int] with \(someInts.count) items.")
//向数组中添加元素
someInts.append(3)
someInts = [] //置空
// someInts现在是一个空得数组,但其始终都是[Int]
Swift的数组类型还提供了一个创建一个数组初始值设定项的一定规模的提供的值设置为默认值。
var threeDoubles = [Double](count: 3,repeatedValue: 0.0)
// threeDoubles数组类型是[Double],其值是 [0.0,0.0,0.0]
数组相加
var anotherThreeDoubles = [Double](count: 3,repeatedValue: 2.5)
// anotherThreeDoubles数组类型是[Double],值为[2.5,2.5,2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
//相加后 sixDoubles数组类型是[Double],值为[0.0,2.5]
使用字面量创建数组
var shoppingList: [String] = ["Egg","Milk"]
//由于数组中值具有相同类型,所以可以不用写数组的类型
//var shoppingList = [“Eggs”,“Milk”]
数组的存取和修改
数组的长度
println("The shopping list contains \(shoppingList.count) items.")
// prints "The shopping list contains 2 items."
//判断数组是否为空
if shoppingList.isEmpty {
println("The shopping list is empty.")
} else {
println("The shopping list is not empty.")
}
shoppingList.append("Chicken")
//也可以使用+=操作符
shoppingList += ["Hen"]
shoppingList += ["Noddle","Beef","Hamburger"]
使用下标语法取数组中的值
var firstItem = shoppingList[0]
改变数组元素对应位置的值
@H_144_301@shoppingList[0] = "Six eggs"
使用下标一次性改变指定范围的值
假设数组中的元素有7个:Six eggs,Milk,Chicken,Hen,Noddle,Beef,Hamburger
//此处的4...6表示将"Noddle","Hamburger"替换成"Bananas","Apples"
shoppingList[4...6] = ["Bananas","Apples"]
在数组的指定位置插入一个元素
shoppingList.insert("Maple Syrup",atIndex: 0)
移除指定位置上元素
shoppingList.removeAtIndex(0)
//移除最后一个元素
shoppingList.removeLast()
数组的迭代访问
可以通过for-in循环来迭代访问整个数组的值
for item in shoppingList {
print("\(item),")
}
如果要获得每个元素的索引及其对应的值,可以使用全局的enumerate方法来迭代使用这个数组.enumerate方法对每个元素都会返回一个由索引值及对应元素值组成的元组。你可以把元组中的成员转为变量或常量来使用 关于元组请看上一节
for (index,value) in enumerate(shoppingList) { print("\nItem \(index + 1): \(value)") }
Set
一个Set集合无序的存储了相同类型的不同的值
创建及初始化
var letters = Set<Character>() println("letters is of type Set<Character> with \(letters.count) items.") // prints "letters is of type Set<Character> with 0 items." letters.insert("s")//插入元素s letters = [];//集合置空
字面量创建Set集合
var favoriteGenres: Set<String> = ["Rock","Classical","Hip hop"]
或者可以使用swift自动类型推导又可以使用如下定义
var favoriteGenres: Set = ["Rock","Hip hop"]
获取集合长度
println("I have \(favoriteGenres.count) favorite music genres")
判断集合是否为空
if favoriteGenres.isEmpty {
println("As far as music goes,I'm not picky.")
} else {
println("I have particular music preferences.")
}
// prints "I have particular music preferences."
插入元素
favoriteGenres.insert("Jazz")
移除元素
if let removedGenre = favoriteGenres.remove("Rock") {
println("\(removedGenre)? I'm over it.")
} else {//Set集合中不包含Rock
println("I never much cared for that.")
}
// prints "Rock? I'm over it."
检查集合是否包含某元素
//包含则返回true
var b = favoriteGenres.contains("Funk") {
迭代遍历Set集合
for genre in favoriteGenres{
println("\(genre)")
}
排序后遍历:使用全局sorted方法,返回一个有序的集合
for genre in sorted(favoriteGenres) {
println("\(genre)")
}
// prints "Classical"
// prints "Hip hop"
// prints "Jazz"
//Set集合比较Compare
let houseAnimals: Set = ["a","b"]
let farmAnimals: Set = ["b","d","e","f"]
let cityAnimals: Set = ["g","h"]
//houseAnimals的所有元素是否被包含在farmAnimals
houseAnimals.isSubsetOf(farmAnimals)// true
//farmAnimals的元素是否包含houseAnimals
farmAnimals.isSupersetOf(houseAnimals)// true
//cityAnimals和farmAnimals中的元素是否有相同的元素
farmAnimals.isDisjointWith(cityAnimals)// true
Dictionary:字典
字典是一种存储多个类型相同的值的容器
Swift的字典对它们能存放的键和值的类型是明确的,且不同Objective-C中的NSDictionary和NSMutableDictionary
创建一个空的字典 Key是Int类型,Value是String类型
var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]
字面量形式创建
var airports: [String: String] = ["YYZ": "Toronto Pearson","DUB": "Dublin"]
不写类型,则自动进行类型推导
var airports = ["YYZ": "Toronto Pearson","DUB": "Dublin"]
字典长度
println("The airports dictionary contains \(airports.count) items.")
//prints "The airports dictionary contains 2 items."
判断字典是否为空
if airports.isEmpty {
println("The airports dictionary is empty.")
} else {
println("The airports dictionary is not empty.")
}
// prints "The airports dictionary is not empty."
添加元素
airports["LHR"] = "London"
修改元素
airports["LHR"] = "London Heathrow"
if let oldValue = airports.updateValue("Dublin Airport",forKey: "DUB"){
println("The old value for DUB was \(oldValue)")
}
// prints "The old value for DUB was Dublin."
if let airportName = airports["DUB"] {
println("The name of the airport is \(airportName).")
} else {
println("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
移除字典中的元素
①根据下标将元素的值设置为nil,若此时字典的键所对应的值为空,则将此键值对从字典中移除
airports["APL"] = "Apple International"
airports["APL"] = nil
②使用方法removeValueForKey
if let removedValue = airports.removeValueForKey("DUB") {
println("The removed airport's name is \(removedValue).")
} else {
println("The airports dictionary does not contain a value for DUB.")
}
// prints "The removed airport's name is Dublin Airport."
字典的遍历
//第一种方式
for (airportCode,airportName) in airports {
println("\(airportCode): \(airportName)")
}
//第二种方式
for airportCode in airports.keys {
println("Airport code: \(airportCode)")
}
//第三种方式
for airportName in airports.values {
println("Airport name: \(airportName)")
}
将字典的键保存到新的数组实例中
let airportCodes = [String](sorted(airports.keys))
// airportCodes is ["YYZ","LHR"]
将字典的值保存到数组实例中
let airportNames = [String](sorted(airports.values))
// airportNames is ["Toronto Pearson","London Heathrow"]
//注意:Swift中的字典类型没有定义顺序,所以迭代特定的顺序的键或者值,可以使用全局排序函数sorted