Swift 學(xué)習(xí)總結(jié)

一,Swift 介紹

? ?Swift 是一門由蘋果公司于2014年WWDC 蘋果開發(fā)者大會上發(fā)布的新的開發(fā)語言,可與Objective-C*共同運行于Mac OSiOS平臺,用于搭建基于蘋果平臺的應(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile麗語閱讀 4,112評論 0 6
  • title: "Swift 中枚舉高級用法及實踐"date: 2015-11-20tags: [APPVENTUR...
    guoshengboy閱讀 2,694評論 0 2
  • 132.轉(zhuǎn)換錯誤成可選值 通過轉(zhuǎn)換錯誤成一個可選值,你可以使用 try? 來處理錯誤。當(dāng)執(zhí)行try?表達(dá)式時,如果...
    無灃閱讀 1,466評論 0 3
  • 西北的早春,是格外單薄的,不要說綠葉,連荒草都是枯敗的,只有薄霧后的太陽少了日常的凌厲,露出一抹紅色的婉約,如一粒...
    我是子非魚閱讀 305評論 1 3
  • 來到高陵上班已經(jīng)半個多月了,雖然天氣還是那樣的寒冷,但是這里很有文化氣息,涇渭分明的誕生地讓我依然感受到八水繞長安...
    思想聚焦的原創(chuàng)閱讀 439評論 0 6

友情鏈接更多精彩內(nèi)容