一,Swift 介紹
? ?Swift 是一門由蘋果公司于2014年WWDC 蘋果開發(fā)者大會上發(fā)布的新的開發(fā)語言,可與Objective-C*共同運行于Mac OS和iOS平臺,用于搭建基于蘋果平臺的應(yīng)用程序。
? 其優(yōu)點:Swift 有類似 Python 的易用性,又有較強(qiáng)的運行效率。既有Objective C的運行時動態(tài)支持,和基于編譯期引用計數(shù)的內(nèi)存管理模型,又具備Ruby靈活優(yōu)雅的語法,C++的嚴(yán)格編譯期檢查、Javascript和Ruby的closure。Swift還支持與Objective C 混編,完美支持IOS/Mac 的SDK。
? 歷史版本:
Swift 4.1 is available as part of?Xcode 9.3.
Swift 4.0.3
Swift 4.0.2
Swift 4.0
Swift 3.1.1
Swift 3.1
Swift 3.0.2
Swift 3.0.1
Swift 3.0
Swift 2.2.1
Swift 2.2
二,簡單示例代碼
`print(“Hello, world!”)`
1,變量和常量
使用 let來聲明一個常量,用 var來聲明一個變量。常量的值在編譯時并不要求已知,但是你必須為其賦值一次。這意味著你可以使用常量來給一個值命名,然后一次定義多次使用。
```
var myVariable = 42
myVariable = 50
let myConstant = 42
```
2,控制流
使用 if和 switch來做邏輯判斷,使用 for-in, for, while,以及 repeat-while來做循環(huán)。使用圓括號把條件或者循環(huán)變量括起來不再是強(qiáng)制的了,不過仍舊需要使用花括號來括住代碼塊。
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
ifscore >50{
teamScore +=3
}else{
teamScore +=1
}
}
print(teamScore)
3,函數(shù)和閉包
使用 func來聲明一個函數(shù)。通過在名字之后在圓括號內(nèi)添加一系列參數(shù)來調(diào)用這個方法。使用 ->來分隔形式參數(shù)名字類型和函數(shù)返回的類型。
func greet(person: String, day: String) -> String {
return"Hello\(person), today is\(day)."
}
greet(person: “Bob”, day: “Tuesday”)
4,對象和類
通過在 class后接類名稱來創(chuàng)建一個類。在類里邊聲明屬性與聲明常量或者變量的方法是相同的,唯一的區(qū)別的它們在類環(huán)境下。同樣的,方法和函數(shù)的聲明也是相同的寫法。
class Shape {
varnumberOfSides =0
funcsimpleDescription()->String{
return"A shape with\(numberOfSides)sides."
}
}
5,枚舉和結(jié)構(gòu)體
使用 enum來創(chuàng)建枚舉,類似于類和其他所有的命名類型,枚舉也能夠包含方法。
enum Rank: Int {
caseace =1
casetwo, three, four, five, six, seven, eight, nine, ten
casejack, queen, king
funcsimpleDescription()->String{
switchself{
case.ace:
return"ace"
case.jack:
return"jack"
case.queen:
return"queen"
case.king:
return"king"
default:
returnString(self.rawValue)
? ? }
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
6,協(xié)議和擴(kuò)展
使用 protocol來聲明協(xié)議。
protocol ExampleProtocol {
varsimpleDescription:String{get}
mutatingfuncadjust()
}
類,枚舉以及結(jié)構(gòu)體都兼容協(xié)議。
class SimpleClass: ExampleProtocol {
var simpleDescription:String="A very simple class."
var anotherProperty:Int=69105
funcadjust(){
simpleDescription +="? Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
varsimpleDescription:String="A simple structure"
mutatingfuncadjust(){
simpleDescription +=" (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
7,錯誤處理
你可以用任何遵循 Error協(xié)議的類型來表示錯誤。
enum PrinterError: Error {
caseoutOfPaper
casenoToner
caseonFire
}
使用 throw來拋出一個錯誤并且用 throws來標(biāo)記一個可以拋出錯誤的函數(shù)。如果你在函數(shù)里拋出一個錯誤,函數(shù)會立即返回并且調(diào)用函數(shù)的代碼會處理錯誤。
func send(job: Int, toPrinter printerName: String) throws -> String {
ifprinterName =="Never Has Toner"{
throwPrinterError.noToner
}
return"Job sent"
}
有好幾種方法來處理錯誤。一種是使用 do-catch。在 do代碼塊里,你用 try來在能拋出錯誤的函數(shù)前標(biāo)記。在catch代碼塊,錯誤會自動賦予名字 error,如果你不給定其他名字的話。
do {
let printerResponse = try send(job:1040, toPrinter:"Bi Sheng")
print(printerResponse)
} catch {
print(error)
}
8,泛型
把名字寫在尖括號里來創(chuàng)建一個泛型方法或者類型。
func makeArray(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..
? ? result.append(item)
}
return result
}
makeArray(repeating: “knock”, numberOfTimes:4)
你可以從函數(shù)和方法同時還有類,枚舉以及結(jié)構(gòu)體創(chuàng)建泛型。
// Reimplement the Swift standard library’s optional type
enum OptionalValue {
casenone
casesome(Wrapped)
}
var possibleInteger: OptionalValue = .none
possibleInteger = .some(100)
在類型名稱后緊接 where來明確一系列需求——比如說,來要求類型實現(xiàn)一個協(xié)議,要求兩個類型必須相同,或者要求類必須繼承自特定的父類。
func anyCommonElements(_ lhs: T, _ rhs: U) -> Bool
where T.Iterator.Element: Equatable, T.Iterator.Element== U.Iterator.Element{
forlhsIteminlhs {
forrhsIteminrhs {
iflhsItem == rhsItem {
returntrue
? ? ? ? ? ? }
? ? ? ? }
? ? }
returnfalse
}
anyCommonElements([1, 2, 3], [3])
三、學(xué)習(xí)及參考資料
https://developer.apple.com/swift/resources/ //?Xcode 9?+?Swift 4 下載
1,Apple 官方Swift 學(xué)習(xí)指南(英文) The Swift Programming Language (Swift 4.1) ? ? ?
??https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1
2,一份翻譯比較完整的中文版Swift 學(xué)習(xí)指南
??https://www.cnswift.org/
3,Swift 評價:
? ?https://www.zhihu.com/question/24002984
4,一個Objective C 代碼 轉(zhuǎn) Swift 代碼的在線網(wǎng)站
??https://objectivec2swift.com/#/converter/
其他參考及學(xué)習(xí)資料:
http://m.itdecent.cn/p/f35514ae9c1a
http://m.itdecent.cn/p/805be373eded
http://m.itdecent.cn/p/563738348597
https://swift.org/download/#releases
https://baike.baidu.com/item/SWIFT/14080957?fr=aladdin
http://m.itdecent.cn/p/69e257a29587?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
http://m.itdecent.cn/p/46c59c647b6e