基础
tuples
// Tuples var address = (number: 142,street: "Evergreen Terrace") //起名 print(address.number) print(address.street) address.0 = 167 print(address.0) //顺序 print(address.1) let (house,street) = address //赋值 print(house) print(street)
strings
// Strings var hello = "Hello" hello = hello + " World" print(hello) // String interpolation print("I live at \(house),\(street)") //替换字符串的内容 let str = "I live at \(house + 10),\(street.uppercaseString)";print(str) //一行多句使用分号
numeric
// Numeric types and conversion var thousands = 1_000 //千元的分隔符(1,000) var radius = 4 let pi = 3.14159 var area = Double(radius) * Double(radius) * pi //类型转换问题
for循环
// For loops and ranges let greeting = "Swift by Tutorials Rocks!" var range = 1...5 //range是一种类型 for i in range { print("\(i) - \(greeting)") }
while循环
// While loops var i = 0 while i < 5 { print("\(i) - \(greeting)") i++ }
if条件
// If statements for i in 1...5 { if i == 5 { print(greeting.uppercaseString) } else { print(greeting) } }
switch
var direction = "up" switch direction { //类型问题 case "down": print("Going Down!") case "up": print("Going Up!") default: print("Going Nowhere") } var score = 570 var prefix: String switch score { case 1..<10: //类型问题 print("novice") case 10..<100: print("proficient") case 100..<1000: print("rock-star") default: print("awesome") }
optional
var str: String! println(str) if let unwrappedStr = str { //解包的方式 println("Unwrapped! \(unwrappedStr.uppercaseString)") } else { println("Was nil") } if str != nil { //解包前的防御式 str = str.lowercaseString println(str) } var maybeString: String? = "Hello Swift by Tutorials!" let uppercase = maybeString?.uppercaseString
array
var array: [Int] = [1,2,3,4,5] println(array[2]) array.append(6) array.extend(7...10) println(array) // Challenge solution: array.removeAtIndex(8) array.removeAtIndex(6) array.removeAtIndex(4) array.removeAtIndex(2) array.removeAtIndex(0) println(array) // Challenge solution: 添加任意类型元素的数组 var anyArray: [AnyObject] = [] anyArray.append(1) anyArray.append("1") println(anyArray)
dictionary
var dictionary: [Int:String] = [1: "Dog",2: "Cat"] println(dictionary[1]) dictionary[3] = "Mouse" dictionary[3] = nil //相当于删除3 println(dictionary) // Challenge solution: dictionary.updateValue("Elephant",forKey: 2) //更改 println(dictionary) println(dictionary[1]) if let value = dictionary[1] { //从字典取出的为optional类型 拆包 println("Value is \(value)") }
set
var setA: Set = [1,3] setA.insert(1) println(setA) setA.remove(1) println(setA) var setB: Set = [2,6] println(setA.intersect(setB)) //交集 // Challenge solution: let divisibleBy3: Set = [3,6,9] let divisibleBy2: Set = [2,8] let union = divisibleBy2.union(divisibleBy3) //并集