let vegetable ="red pepper" switch vegetable { let vegetableComment ="Add some raisins and make ants on a log." case"cucumber", "watercress": let vegetableComment ="That would make a good tea sandwich." caselet x where x.hasSuffix("pepper"): let vegetableComment ="Is it a spicy \(x)?" default: let vegetableComment ="Everything tastes good in soup." }
let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest =0 for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } } largest
使用while来重复运行一段代码直到不满足条件。循环条件可以在开头也可以在结尾。
1 2 3 4 5 6 7 8 9 10 11
var n =2 while n <100 { n = n *2 } n
var m =2 do { m = m *2 } while m <100 m
你可以在循环中使用..来表示范围,也可以使用传统的写法,两者是等价的:
1 2 3 4 5 6 7 8 9 10 11
var firstForLoop =0 for i in0..3 { firstForLoop += i } firstForLoop
var secondForLoop =0 forvar i =0; i <3; ++i { secondForLoop +=1 } secondForLoop
函数和闭包
使用func来声明一个函数,使用名字和参数来调用函数,使用->来指定函数返回值
1 2 3 4
funcgreet(name:String,day:String) -> String{ return"Hello \(name),today is \(day)." } greet("Bob","Tuesday")
overridefuncsimpleDescription() -> String { return"A square with sides of length \(sideLength)." } } let test =Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()
structCard{ var rank:Rank var suit:Suit funcsimpleDescription() -> String { return"The \(rank.simpleDescription()) of \(suit.simpleDescription)" } } let threeOfSpades =Card(rank: .Three,suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simleDescription()
协议和扩展
使用protocol来声明一个协议
1 2 3 4
protocolExampleProtocol { var simpleDescription: String{get} mutatingfuncadjust() }
classSimpleClass:ExampleProtocol { var simpleDescription:String="A very simple class" var anotherProperty: Int=69105 funcadjust(){ simpleDescription +="Noew 100% adjusted." } } var a =SimpleClass() a.adjust() let aDescription = a.simpleDescription
structSimpleStructire:ExampleProtocol{ var simpleDescription:String="A simple structure" mutatingfuncadjust(){ simpleDescription +="(adjust)" } } var b =SimpleStructire() b.adjust() let bDescruption = b.simpleDescription
声明的时候mutating关键字用来标记一个会修改结构体的方法。
使用extension来为现有的类型添加功能,比如新的方法和参数。
1 2 3 4 5 6 7 8 9
extensionInt: ExampleProtocol{ var simpleDescription:String{ return"The number \(self)" } mutatingfuncadjust(){ self+=42 } } 7.simpleDescription
let protocolValue: ExampleProtocol= a protocolValue.simpleDescription // protocolValue.anotherProperty // Uncomment to see the error
泛型
在尖括号里写一个名字来创建一个泛型函数或者类型
1 2 3 4 5 6 7 8
funcrepeat<ItemType>(item: ItemType,times:Int) -> ItemType[]{ var result =ItemType[]() for i in0..times{ result += item } return result } repeat("knock",4)