// 字符串中轉換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* numberreturn result
})
// 閉包類型已知,可以去掉參數類型和返回類型let mappedNumbers = numbers.map({ number in3* number})print(mappedNumbers)
// 初始化器classNameShape{var numberOfSides:Int=0var name:Stringinit(name:String){self.name = name}funcsimpleDescription()->String{return"A shape with \(numberOfSides) sides."}}
// 子類重寫父類的實現classSquare:NameShape{var sideLength:Doubleinit(sideLength:Double, name:String){self.sideLength = sideLengthsuper.init(name: name)numberOfSides =4}funcarea()->Double{return sideLength * sideLength}overridefuncsimpleDescription()->String{return"A square with sides of length \(sideLength)."}}let test =Square(sideLength:5.2, name:"my test square")var d = test.area()
s = test.simpleDescription()
// 計算屬性classEquilateralTriangle:NameShape{var sideLength:Double=0.0init(sideLength:Double, name:String){self.sideLength = sideLengthsuper.init(name: name)numberOfSides =3}var perimeter:Double{get{return3.0* sideLength}set{sideLength = newValue /3.0}}overridefuncsimpleDescription()->String{return"An equilateral triangle with sides of length \(sideLength)."}}
// 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)
// 類、枚舉以及結構體都兼容協議,mutating關鍵字來聲明使方法可以修改結構體,類中不需要這樣聲明classSimpleClass:ExampleProtocol{var simpleDescription:String="A very simple class."var anothorProperty:Int=69105funcadjust(){simpleDescription +=" Now 100% adjusted."}}var aa =SimpleClass()
aa.adjust()let aDescription = aa.simpleDescriptionstructSimpleStructure:ExampleProtocol{var simpleDescription:String="A simple structure"mutatingfuncadjust(){simpleDescription +=" (adjusted)"}}var bb =SimpleStructure()
bb.adjust()let bDescription = bb.simpleDescription
// 使用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)
// 提供多個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)
1. 從啟動類開始
public static void main(String[] args) {// Run the SpringApplication class with the Application class as the first argumentSpringApplication.run(Application.class, args);}2. bean 實例化
// SpringAplication row1294,1295
run()
// SpringApli…