Swift 學習總結(jié)(持續(xù)更新)

一,Swift 介紹

Swift 是一門由蘋果公司于2014年WWDC 蘋果開發(fā)者大會上發(fā)布的新的開發(fā)語言,可與Objective-C*共同運行于Mac OSiOS平臺,用于搭建基于蘋果平臺的應(yīng)用程序。

其優(yōu)點:Swift 有類似 Python 的易用性,又有較強的運行效率。既有Objective C的運行時動態(tài)支持,和基于編譯期引用計數(shù)的內(nèi)存管理模型,又具備Ruby靈活優(yōu)雅的語法,C++的嚴格編譯期檢查、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)變量括起來不再是強制的了,不過仍舊需要使用花括號來括住代碼塊。

let individualScores = [75, 43, 103, 87, 12]
        
        var teamScore = 0
        
        for score in individualScores {
            
            if score>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 {
    
    var numberOfSides = 0
    
    func simpleDescription()->String{
    
    return"A shape with\(numberOfSides)sides."
    
    }
}

5,枚舉和結(jié)構(gòu)體

使用 enum來創(chuàng)建枚舉,類似于類和其他所有的命名類型,枚舉也能夠包含方法。

enum Rank:Int {
    
    case ace = 1
    
    case two, three, four, five, six, seven, eight, nine, ten
    
    case jack, queen, king
    
    func simpleDescription()->String{
        
        switch self{
            
        case.ace:
            
            return"ace"
            
        case.jack:
            
            return"jack"
            
        case.queen:
            
            return"queen"
            
        case.king:
            
            return"king"
            
        default:
            
            return String(self.rawValue)
            
        }
        
    }
    
}

init() {
        
        let ace = Rank.ace
        
        let aceRawValue = ace.rawValue
    }

6,協(xié)議和擴展

使用 protocol來聲明協(xié)議。

protocol ExampleProtocol {
    
    var simpleDescription:String{get}
    
    func mutatingfuncadjust()
    
}

類,枚舉以及結(jié)構(gòu)體都兼容協(xié)議。

protocol ExampleProtocol {
    
    var simpleDescription:String{get}
    
    func adjust()
    
}

class SimpleClass:ExampleProtocol {
    
    var simpleDescription:String="A very simple class."
    
    var anotherProperty:Int=69105
    
    func adjust(){
    
        simpleDescription += "  Now 100% adjusted."
    
    }
    
}

struct SimpleStructure: ExampleProtocol {
    
    var simpleDescription:String="A simple structure"
    
    func adjust(){
        
        // Left side of mutating operator isn't mutable: 'self' is immutable
    
    }
    
}

class test {
    
    init() {
        
        var a = SimpleClass()
        
        a.adjust()
        
        let aDescription = a.simpleDescription
        
        var b = SimpleStructure()
        
        b.adjust()
        
        let bDescription = b.simpleDescription
    }
    
    
}

7,錯誤處理

你可以用任何遵循 Error協(xié)議的類型來表示錯誤。

enum PrinterError: Error {
    
    case outOfPaper
    
    case noToner
    
    case onFire
    
}

使用 throw來拋出一個錯誤并且用 throws來標記一個可以拋出錯誤的函數(shù)。如果你在函數(shù)里拋出一個錯誤,函數(shù)會立即返回并且調(diào)用函數(shù)的代碼會處理錯誤。

func send(job: Int, toPrinter printerName: String) throws -> String {
        
        if printerName == "Never Has Toner"{
            
            throw PrinterError.noToner
            
        }
        
        return"Job sent"
    }

有好幾種方法來處理錯誤。一種是使用 do-catch。在 do代碼塊里,你用 try來在能拋出錯誤的函數(shù)前標記。在catch代碼塊,錯誤會自動賦予名字 error,如果你不給定其他名字的話。

do {

let printerResponse = try send(job:1040, toPrinter:"Bi Sheng")

print(printerResponse)

} catch {

print(error)

}

8,泛型

把名字寫在尖括號里來創(chuàng)建一個泛型方法或者類型。

class Item {
    
    var a = "a"
    var b = "b"
}

func makeArray(repeating item: Item, numberOfTimes: Int) -> [Item] {

        var result = [Item]()

        //for _ in 0..

        result.append(item)

        return result

}
    
init() {
        var item = Item()
        makeArray(repeating:item, numberOfTimes:4)
 }

你可以從函數(shù)和方法同時還有類,枚舉以及結(jié)構(gòu)體創(chuàng)建泛型。

// Reimplement the Swift standard library’s optional type

enum OptionalValue {
        
        case none
        
        case some(Int)
        
}

init() {
    
        var possibleInteger: OptionalValue = .none
        
        possibleInteger = .some(100)
 }

在類型名稱后緊接 where來明確一系列需求——比如說,判斷兩個數(shù)組中否包含有相同的對象(不是地址相等,是內(nèi)容相等

func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
        where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
            for lhsItem in lhs {
                for rhsItem in rhs {
                    if lhsItem == rhsItem {
                        return true
                    }
                }
            }
            return false
    }


返回獲取相交的數(shù)據(jù)

func anyCommonElements<T: Sequence, U: Sequence >(_ lhs: T, _ rhs: U) -> Array<T.Iterator.Element>
        where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element{
            var array:[T.Iterator.Element] = Array()
            for lhsItem in lhs {
                for rhsItem in rhs {
                    if lhsItem == rhsItem {
                        array.append(lhsItem)
                    }
                }
            }
            return array
    }

三、學習及參考資料

https://developer.apple.com/swift/resources/ // Xcode 9 + Swift 4 下載

1,Apple 官方Swift 學習指南(英文) 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 學習指南

https://www.cnswift.org/

3,Swift 評價:

https://www.zhihu.com/question/24002984

4,一個Objective C 代碼 轉(zhuǎn) Swift 代碼的在線網(wǎng)站

https://objectivec2swift.com/#/converter/

其他參考及學習資料:

http://www.itdecent.cn/p/f35514ae9c1a

http://www.itdecent.cn/p/805be373eded

http://www.itdecent.cn/p/563738348597

https://swift.org/download/#releases

https://baike.baidu.com/item/SWIFT/14080957?fr=aladdin

http://www.itdecent.cn/p/69e257a29587?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

http://www.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)容

  • 一直沒有時間好好看一下swift,最近復(fù)習了一遍語法,這里記錄swift學習過程中遇到的一些問題和要點,和Obje...
    bomo閱讀 2,563評論 0 25
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,319評論 25 708
  • 有圖有真相↑ 有點粗淺的思維匯總,不建議參考。 期望它可以給大家一點好的認知。 我說的...
    進擊的野蠻生長閱讀 549評論 0 0
  • 和你一樣,我們都是這世間最普通,又最唯一的小塵埃。寫這些東西的初衷只是想把它們記錄下來。也許文采并沒有斐然,也許盡...
    公子瀾卿閱讀 174評論 1 0
  • 學習計算機網(wǎng)絡(luò)的核心就是學習網(wǎng)絡(luò)協(xié)議。 1,什么是網(wǎng)絡(luò)協(xié)議呢? 它是為了計算機網(wǎng)絡(luò)中的數(shù)據(jù)交換而建立的一系列規(guī)則,...
    凍桃花閱讀 492評論 0 0

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