Swift 字符串+集合(三)

Strings and Characters 字符串和字符

String Literals 字符串字面量
用於爲常量或變量提供初始值,可包含以下特殊字符
轉義字符\0(空)、\\(反斜線)、\t(水平製表)、\n(換行)、\r(回車)、\"(雙引號)、\'(單引號)
單字節Unicode , 寫成\xnn,nn爲兩位十六進制數
雙字節Unicode , 寫成\unnnn,nnnn爲四位十六進制數
四字節Unicode , 寫成\Unnnnnnnn,nnnnnnnn爲八位十六進制數


Initializing an Empty String 初始化空字符串
var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax
// these two strings are both empty, and are equivalent to each other
通過檢查isEmpty屬性判斷是否爲空
if emptyString.isEmpty {
    println("Nothing to see here")
}
// prints "Nothing to see here"

String Mutability 字符串的可變性
將字符串賦給變量來進行修改,或分配給常量來保證不被修改
var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
 
let constantString = "Highlander"
constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified

Strings Are Value Types 值類型
Swift的String是值類型,如果創建了一個新的字符串,當進行常量、變量賦值或在函數、方法中傳遞的時候都會進行值拷貝,In each case, a new copy of the existing String value is created, and the new copy is passed or assigned, not the original version.

Working with Characters 使用字符
String類型即Character字符的集合,每個字符代表一個Unicode字符,可用for-in循環來遍歷字符串中的值
for character in "Dog!" {
    println(character)
}
// D
// o
// g
// !
或者,通過標明一個Character的類型並進行賦值,可聲明一個獨立的字符常量或變量
let yenSign: Character = "¥"

Counting Characters 計算字符數
調用全局的countElements函數計算字符串的字符數量,(有幾個表情我省略了,想知道是什麼看原文)
let unusualMenagerie = "Koala , Snail , Penguin , Dromedary "
println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"

Concatenating Strings and Characters 連接字符串和字符
let string1 = "hello"
let string2 = " there"
let character1: Character = "!"
let character2: Character = "?"
 
let stringPlusCharacter = string1 + character1        // equals "hello!"
let stringPlusString = string1 + string2              // equals "hello there"
let characterPlusString = character1 + string1        // equals "!hello"
let characterPlusCharacter = character1 + character2  // equals "!?"


var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
 
var welcome = "good morning"
welcome += character1
// welcome now equals "good morning!"

String Interpolation 插值
寫在括號中的表達式不能包含非轉義雙引號("")和反斜槓(\),回車和換行符
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"

Comparing Strings 字符串比較
String Equality 字符串相等,兩個字符串完全相等,兩者才相等
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
Prefix and Suffix Equality 前綴/後綴相等
let romeoAndJuliet = [
    "Act 1 Scene 1: Verona, A public place",
    "Act 1 Scene 2: Capulet's mansion",
    "Act 1 Scene 3: A room in Capulet's mansion",
    "Act 1 Scene 4: A street outside Capulet's mansion",
    "Act 1 Scene 5: The Great Hall in Capulet's mansion",
    "Act 2 Scene 1: Outside Capulet's mansion",
    "Act 2 Scene 2: Capulet's orchard",
    "Act 2 Scene 3: Outside Friar Lawrence's cell",
    "Act 2 Scene 4: A street in Verona",
    "Act 2 Scene 5: Capulet's mansion",
    "Act 2 Scene 6: Friar Lawrence's cell"
]

var act1SceneCount = 0
for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
        ++act1SceneCount
    }
}
println("There are \(act1SceneCount) scenes in Act 1")
// prints "There are 5 scenes in Act 1"

var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
    if scene.hasSuffix("Capulet's mansion") {
        ++mansionCount
    } else if scene.hasSuffix("Friar Lawrence's cell") {
        ++cellCount
    }
}
println("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// prints "6 mansion scenes; 2 cell scenes"

Uppercase and Lowercase Strings 大寫和小寫
let normal = "Could you help me, please?"
let shouty = normal.uppercaseString
// shouty is equal to "COULD YOU HELP ME, PLEASE?"
let whispered = normal.lowercaseString
// whispered is equal to "could you help me, please?"




Collection Type 集合類型

Swift提供數組和字典兩種集合類型來存儲數據,數組按順序存儲,字典按鍵值對存儲

Arrays 數組

創建數組
由一系列逗號分隔並由方括號包含,以下定義一個字符串類型數組,爲String[],由於Swift會自動判斷所定義的變量的類型,所以String[] 也可以省略
var shoppingList: String[] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
// var shoppingList = ["Eggs", "Milk"]

var someInts = Int[]()
println("someInts is of type Int[] with \(someInts.count) items.")
// prints "someInts is of type Int[] with 0 items."

var threeDoubles = Double[](count: 3, repeatedValue: 0.0)
// threeDoubles is of type Double[], and equals [0.0, 0.0, 0.0]

var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
// anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]

訪問和修改數組的值
可通過數組的方法和屬性,或者下標來使用數組,等等等等,以下代碼推薦使用在Xcode6下看一遍,加深體會
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.")
}
// prints "The shopping list is not empty."

shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes

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"]
// shoppingList now contains 6 items

shoppingList.insert("Maple Syrup", atIndex: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list

let mapleSyrup = shoppingList.removeAtIndex(0)
// 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]
// firstItem is now equal to "Six eggs"

let apples = shoppingList.removeLast()
// the last item in the array has just been removed
// shoppingList now contains 5 items, and no cheese
// the apples constant is now equal to the removed "Apples" string

var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as Double[], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

遍歷數組
for item in shoppingList {
    println(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
或者使用全局enumerate函數來對數組進行遍歷,enumerate返回一個索引和一個數據值
for (index, value) in enumerate(shoppingList) {
    println("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas

字典

字典中的數據是無須的,通過鍵來取數據,不同於OC中的NSDictionary 和 NSMutableDictionary可以用任意類型的對象來做鍵和值,Swift中必須提前聲明

定義字典,airport定義爲Dictionary<String,String>,意味着字典的鍵和值都是String類型的
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"]
// var airports = ["TYO": "Tokyo", "DUB": "Dublin"]

var namesOfIntegers = Dictionary<Int, String>()
// namesOfIntegers is an empty Dictionary<Int, String>

對字典進行操作
通過字典的方法、屬性和下標進行操作
println("The dictionary of airports contains \(airports.count) items.")
// prints "The dictionary of airports contains 2 items."

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

if let oldValue = airports.updateValue("Dublin International", 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 International."

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

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 International."


字典的遍歷

for (airportCode, airportName) in airports {
    println("\(airportCode): \(airportName)")
}
// TYO: Tokyo
// LHR: London Heathrow

for airportCode in airports.keys {
    println("Airport code: \(airportCode)")
}
// Airport code: TYO
// Airport code: LHR
 
for airportName in airports.values {
    println("Airport name: \(airportName)")
}
// Airport name: Tokyo
// Airport name: London Heathrow

let airportCodes = Array(airports.keys)
// airportCodes is ["TYO", "LHR"]
 
let airportNames = Array(airports.values)
// airportNames is ["Tokyo", "London Heathrow"]



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章