// 字符串中转换let apples =3let appleSummary ="I have \(apples) apples"
// 多行内容let quotation ="""
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being wscaped.
I still have \(apples) pieces of fruit.
"""
// 创建数组var shoppingList =["catfish","water","tulips","blue paint"]
shoppingList[1]="bottle of water"
// Switch 选择语句支持任意类型的数据和各种类型的比较操作,不再限制于整型和测试相等let vegetable ="red pepper"switch vegetable {case"celery":print("Add some raisins and make ants on a log.")case"cucumber","watercress":print("That would make a good tea sandwich.")caselet x where x.hasSuffix("pepper"):print("Is it a spicy \(x)?")default:print("Everything tastes good in soup.")}
// for-in遍历字典let interestingNumbers =["Prime":[2,3,5,7,11,13],"Fibonacci":[1,1,2,3,5,8],"Square":[1,4,9,16,25],]var largest =0for(_, numbers)in interestingNumbers {for number in numbers {if number > largest {
largest = number
}}}
// whilevar n =2while n <100{
n = n *2}var m =2repeat{
m = m *2}while m <100
// ..创造序列区间var total =0for i in0..<4{
total += i
}
函数和闭包
// func声明函数funcgreet(person:String, day:String)->String{return"Hello \(person), today is \(day)"}var s =greet(person:"Bob", day:"Tuesday")
// 默认使用形参作为实参,可以在形参前自定义实参名或者使用_避免使用实参funcgreet(_ person:String, on day:String)->String{return"Hello \(person), today is \(day)"}
s =greet("John", on:"Wednesday")
// 使用元祖来创建复合值funccalculateStatics(scores:[Int])->(min:Int, max:Int, sum:Int){var min = scores[0]var max = scores[0]var sum =0for score in scores {if score > max {
max = score
}elseif score < min {
min = score
}
sum += score
}return(min, max, sum)}let statistics =calculateStatics(scores:[5,3,100,3,9])print(statistics.sum)print(statistics.2)
// 函数接受多个参数存放在数组中funcsumOf(numbers:Int...)->Int{var sum =0for number in numbers {
sum += number
}return sum
}var i =sumOf()
i =sumOf(numbers:42,597,12)
// 内嵌函数可以访问外部函数里的变量funcreturnFifteen()->Int{var y =10funcadd(){
y +=5}add()return y
}
i =returnFifteen()
// 函数是一等类型,函数可以把函数作为值来返回funcmakeIncrementer()->((Int)->Int){funcaddOne(number:Int)->Int{return1+ number
}return addOne
}var increment =makeIncrementer()
i =increment(7)
// 函数可以做参数funchasAnyMatches(list:[Int], condition:(Int)->Bool)->Bool{for item in list {ifcondition(item){returntrue}}returnfalse}funclessThanTen(number:Int)->Bool{return number <10}var numbers =[20,19,7,12]var b =hasAnyMatches(list: numbers, condition: lessThanTen)
// 闭包中用in分割实际参数和返回类型var a = numbers.map({(number:Int)->Intinlet result =3* number
return result
})
// 闭包类型已知,可以去掉参数类型和返回类型let mappedNumbers = numbers.map({ number in3* number})print(mappedNumbers)
// case与值关联,值在初始化实例的时候确定,这样它们就可以在每个实例中不同了enumServerResponse{caseresult(String,String)casefailure(String)}let success =ServerResponse.result("6:00 am","8:09 pm")let failure =ServerResponse.failure("Out of cheese.")switch success {caselet.result(sunrise, sunset):print("Sunrise is at \(sunrise) and sunset is at \(sunset)")caselet.failure(message):print("Failure... \(message)")}
// 使用任务组来构造并发代码let userIDs =awaitwithTaskGroup(of:Int.self){ group infor server in["primary","secondary","development"]{
group.addTask {returnawaitfetchUserID(from: server)}}var results:[Int]=[]forawait result in group {
results.append(result)}return results
}print(userIDs)
// 使用extension来给现存的类型增加功能extensionInt:ExampleProtocol{var simpleDescription:String{return"The number \(self)"}mutatingfuncadjust(){self+=42}}print(7.simpleDescription)
// 当操作类型是协议类型的值的时候,协议外定义的方法是不可用的let protocolValue:ExampleProtocol= aa
print(protocolValue.simpleDescription)// print(protocolValue.anothorProperty)
错误处理
// 用任何遵循Error协议的类型来表示错误enumPrinterError:Error{case outOfPaper
case noToner
case onFire
}
// 使用throw来抛出错误并且用throws标记一个可以抛出错误的函数。如果在函数里抛出一个错误,函数会立即返回并且调用函数的代码处理错误funcsend(job:Int, toPrinter printerName:String)throws->String{if printerName =="Never Has Toner"{throwPrinterError.noToner
}return"Job sent"}
// 提供多个catch代码块来处理特定的错误,用法和switch里的case一样do{let printResponse =trysend(job:1440, toPrinter:"Gutenberg")print(printResponse)}catchPrinterError.onFire {print("I'll just put this over here, with the rest of the fire")}catchlet printerError asPrinterError{print("Printer error: \(printerError).")}catch{print(error)}
// 使用try?来转换结果为可选项。如果函数抛出了错误,那么错误被忽略并且结果为nil。否则,结果是一个包含了函数返回值的可选项let printerSuccess =try?send(job:1884, toPrinter:"Mergenthaler")let printerFailure =try?send(job:1885, toPrinter:"Never Has Toner")
// 使用defer来写函数返回后也会被执行的代码,无论是否错误被抛出。甚至可以在没有任何错误处理的时候使用defer,来简化需要在多处地方返回的函数。var fridgeIsOpen =falselet fridgeContent =["milk","eggs","leftovers"]funcfridgeContains(_ food:String)->Bool{
fridgeIsOpen =truedefer{
fridgeIsOpen =false}print(fridgeIsOpen)let result = fridgeContent.contains(food)return result
}
b =fridgeContains("banana")print(fridgeIsOpen)
泛型
// 创建一个泛型方法或者类型funcmakeArray<Item>(repeating item:Item, numberOfTimes:Int)->[Item]{var result =[Item]()for_in0..<numberOfTimes {
result.append(item)}return result
}var aes =makeArray(repeating:"knock", numberOfTimes:4)print(aes)