Swift學習筆記(二)字符串和集合類型操作

字符串操作

創建字符串常量

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, 0.0, 0.0, 2.5, 2.5, 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.")
}

使用append方法添加元素(在數組尾部添加元素)

shoppingList.append("Chicken")
//也可以使用+=操作符
shoppingList += ["Hen"]
shoppingList += ["Noddle", "Beef", "Hamburger"]

使用下標語法取數組中的值

var firstItem = shoppingList[0]

改變數組元素對應位置的值

shoppingList[0] = "Six eggs"

使用下標一次性改變指定範圍的值
假設數組中的元素有7個:Six eggs, Milk, Chicken, Hen, Noddle, Beef, Hamburger

//此處的4...6表示將"Noddle","Beef","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 shoppingList.enumerate() {
    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", "Classical", "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", "a", "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

發佈了33 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章