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"]



你可能感兴趣的:(ios,swift,苹果)