自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

蘋果的新編程語言 Swift 簡介

移動開發(fā) iOS
上一次某家大公司大張旗鼓的推出一門編程語言及其編程平臺還是在2000年(微軟推出C#),將近15年之后,蘋果推出Swift——作為開發(fā)者,我很高興能夠見證一門編程語言的誕生。

這篇文章簡要介紹了蘋果于WWDC 2014發(fā)布的編程語言——Swift。

前言

在這里我認(rèn)為有必要提一下Brec VictorInventing on Principle,Swift編程環(huán)境的大部分概念都源自于Brec這個演講。

接下來進(jìn)入正題。

Swift是什么?

Swift是蘋果于WWDC 2014發(fā)布的編程語言,這里引用The Swift Programming Language的原話:

Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to imagine how software development works. Swift is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.

簡單的說:

  1. Swift用來寫iOS和OS X程序。(估計也不會支持其它屌絲系統(tǒng))
  2. Swift吸取了C和Objective-C的優(yōu)點(diǎn),且更加強(qiáng)大易用。
  3. Swift可以使用現(xiàn)有的Cocoa和Cocoa Touch框架。
  4. Swift兼具編譯語言的高性能(Performance)和腳本語言的交互性(Interactive)。

Swift語言概覽

基本概念

注:這一節(jié)的代碼源自The Swift Programming Language中的A Swift Tour。

Hello, world

類似于腳本語言,下面的代碼即是一個完整的Swift程序。

  1. println("Hello, world"

變量與常量

Swift使用var聲明變量,let聲明常量

  1. var myVariable = 42 
  2. myVariable = 50 
  3. let myConstant = 42 

類型推導(dǎo)

Swift支持類型推導(dǎo)(Type Inference),所以上面的代碼不需指定類型,如果需要指定類型:

  1. let explicitDouble : Double = 70 

Swift不支持隱式類型轉(zhuǎn)換(Implicitly casting),所以下面的代碼需要顯式類型轉(zhuǎn)換(Explicitly casting):

  1. let label = "The width is " 
  2. let width = 94 
  3. let width = label + String(width) 

字符串格式化

Swift使用\(item)的形式進(jìn)行字符串格式化:

  1. let apples = 3 
  2. let oranges = 5 
  3. let appleSummary = "I have \(apples) apples." 
  4. let appleSummary = "I have \(apples + oranges) pieces of fruit." 

數(shù)組和字典

Swift使用[]操作符聲明數(shù)組(array)和字典(dictionary):

  1. var shoppingList = ["catfish""water""tulips""blue paint"
  2. shoppingList[1] = "bottle of water" 
  3.   
  4. var occupations = [ 
  5.     "Malcolm""Captain"
  6.     "Kaylee""Mechanic"
  7. occupations["Jayne"] = "Public Relations" 

一般使用初始化器(initializer)語法創(chuàng)建空數(shù)組和空字典:

  1. let emptyArray = String[]() 
  2. let emptyDictionary = Dictionary<String, Float>() 

如果類型信息已知,則可以使用[]聲明空數(shù)組,使用[:]聲明空字典。

控制流

概覽

Swift的條件語句包含if和switch,循環(huán)語句包含for-in、for、while和do-while,循環(huán)/判斷條件不需要括號,但循環(huán)/判斷體(body)必需括號:

  1. let individualScores = [75, 43, 103, 87, 12] 
  2. var teamScore = 0 
  3. for score in individualScores { 
  4.     if score > 50 { 
  5.         teamScore += 3 
  6.     } else { 
  7.         teamScore += 1 
  8.     } 

可空類型

結(jié)合if和let,可以方便的處理可空變量(nullable variable)。對于空值,需要在類型聲明后添加?顯式標(biāo)明該類型可空。

  1. var optionalString: String? = "Hello" 
  2. optionalString == nil 
  3.   
  4. var optionalName: String? = "John Appleseed" 
  5. var gretting = "Hello!" 
  6. if let name = optionalName { 
  7.     gretting = "Hello, \(name)" 

靈活的switch

Swift中的switch支持各種各樣的比較操作:

  1. let vegetable = "red pepper" 
  2. switch vegetable { 
  3. case "celery"
  4.     let vegetableComment = "Add some raisins and make ants on a log." 
  5. case "cucumber""watercress"
  6.     let vegetableComment = "That would make a good tea sandwich." 
  7. case let x where x.hasSuffix("pepper"): 
  8.     let vegetableComment = "Is it a spicy \(x)?" 
  9. default
  10.     let vegetableComment = "Everything tastes good in soup." 

其它循環(huán)

for-in除了遍歷數(shù)組也可以用來遍歷字典:

  1. let interestingNumbers = [ 
  2.     "Prime": [2, 3, 5, 7, 11, 13], 
  3.     "Fibonacci": [1, 1, 2, 3, 5, 8], 
  4.     "Square": [1, 4, 9, 16, 25], 
  5. var largest = 0 
  6. for (kind, numbers) in interestingNumbers { 
  7.     for number in numbers { 
  8.         if number > largest { 
  9.             largest = number 
  10.         } 
  11.     } 
  12. largest 

while循環(huán)和do-while循環(huán):

  1. var n = 2 
  2. while n < 100 { 
  3.     n = n * 2 
  4.   
  5. var m = 2 
  6. do { 
  7.     m = m * 2 
  8. while m < 100 

Swift支持傳統(tǒng)的for循環(huán),此外也可以通過結(jié)合..(生成一個區(qū)間)和for-in實(shí)現(xiàn)同樣的邏輯。

  1. var firstForLoop = 0 
  2. for i in 0..3 { 
  3.     firstForLoop += i 
  4. firstForLoop 
  5.   
  6. var secondForLoop = 0 
  7. for var i = 0; i < 3; ++i { 
  8.     secondForLoop += 1 
  9. secondForLoop 

注意:Swift除了..還有...:..生成前閉后開的區(qū)間,而...生成前閉后閉的區(qū)間。

函數(shù)和閉包

函數(shù)

Swift使用func關(guān)鍵字聲明函數(shù):

  1. func greet(name: String, day: String) -> String { 
  2.     return "Hello \(name), today is \(day)." 
  3. greet("Bob""Tuesday"

通過元組(Tuple)返回多個值:

  1. func getGasPrices() -> (Double, Double, Double) { 
  2.     return (3.59, 3.69, 3.79) 
  3. getGasPrices() 

支持帶有變長參數(shù)的函數(shù):

  1. func sumOf(numbers: Int...) -> Int { 
  2.     var sum = 0 
  3.     for number in numbers { 
  4.         sum += number 
  5.     } 
  6.     return sum 
  7. sumOf() 
  8. sumOf(42, 597, 12) 

函數(shù)也可以嵌套函數(shù):

  1. func returnFifteen() -> Int { 
  2.     var y = 10 
  3.     func add() { 
  4.         y += 5 
  5.     } 
  6.     add() 
  7.     return y 
  8. returnFifteen() 

作為頭等對象,函數(shù)既可以作為返回值,也可以作為參數(shù)傳遞:

  1. func makeIncrementer() -> (Int -> Int) { 
  2.     func addOne(number: Int) -> Int { 
  3.         return 1 + number 
  4.     } 
  5.     return addOne 
  6. var increment = makeIncrementer() 
  7. increment(7)
  1. func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { 
  2.     for item in list { 
  3.         if condition(item) { 
  4.             return true 
  5.         } 
  6.     } 
  7.     return false 
  8. func lessThanTen(number: Int) -> Bool { 
  9.     return number < 10 
  10. var numbers = [20, 19, 7, 12] 
  11. hasAnyMatches(numbers, lessThanTen) 

閉包

本質(zhì)來說,函數(shù)是特殊的閉包,Swift中可以利用{}聲明匿名閉包:

  1. numbers.map({ 
  2.     (number: Int) -> Int in 
  3.     let result = 3 * number 
  4.     return result 
  5.     }) 

當(dāng)閉包的類型已知時,可以使用下面的簡化寫法:

  1. numbers.map({ number in 3 * number }) 

此外還可以通過參數(shù)的位置來使用參數(shù),當(dāng)函數(shù)最后一個參數(shù)是閉包時,可以使用下面的語法:

  1. sort([1, 5, 3, 12, 2]) { $0 > $1 } 

類和對象

創(chuàng)建和使用類

Swift使用class創(chuàng)建一個類,類可以包含字段和方法:

  1. class Shape { 
  2.     var numberOfSides = 0 
  3.     func simpleDescription() -> String { 
  4.         return "A shape with \(numberOfSides) sides." 
  5.     } 

創(chuàng)建Shape類的實(shí)例,并調(diào)用其字段和方法。

  1. var shape = Shape() 
  2. shape.numberOfSides = 7 
  3. var shapeDescription = shape.simpleDescription() 

通過init構(gòu)建對象,既可以使用self顯式引用成員字段(name),也可以隱式引用(numberOfSides)。

  1. class NamedShape { 
  2.     var numberOfSides: Int = 0 
  3.     var name: String 
  4.   
  5.     init(name: String) { 
  6.         self.name = name 
  7.     } 
  8.   
  9.     func simpleDescription() -> String { 
  10.         return "A shape with \(numberOfSides) sides." 
  11.     } 

使用deinit進(jìn)行清理工作。

繼承和多態(tài)

Swift支持繼承和多態(tài)(override父類方法):

  1. class Square: NamedShape { 
  2.     var sideLength: Double 
  3.   
  4.     init(sideLength: Double, name: String) { 
  5.         self.sideLength = sideLength 
  6.         super.init(name: name) 
  7.         numberOfSides = 4 
  8.     } 
  9.   
  10.     func area() -> Double { 
  11.         return sideLength * sideLength 
  12.     } 
  13.   
  14.     override func simpleDescription() -> String { 
  15.         return "A square with sides of length \(sideLength)." 
  16.     } 
  17. let test = Square(sideLength: 5.2, name: "my test square"
  18. test.area() 
  19. test.simpleDescription() 

注意:如果這里的simpleDescription方法沒有被標(biāo)識為override,則會引發(fā)編譯錯誤。

屬性

為了簡化代碼,Swift引入了屬性(property),見下面的perimeter字段:

  1. class EquilateralTriangle: NamedShape { 
  2.     var sideLength: Double = 0.0 
  3.   
  4.     init(sideLength: Double, name: String) { 
  5.         self.sideLength = sideLength 
  6.         super.init(name: name) 
  7.         numberOfSides = 3 
  8.     } 
  9.   
  10.     var perimeter: Double { 
  11.     get { 
  12.         return 3.0 * sideLength 
  13.     } 
  14.     set { 
  15.         sideLength = newValue / 3.0 
  16.     } 
  17.     } 
  18.   
  19.     override func simpleDescription() -> String { 
  20.         return "An equilateral triagle with sides of length \(sideLength)." 
  21.     } 
  22. var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle"
  23. triangle.perimeter 
  24. triangle.perimeter = 9.9 
  25. triangle.sideLength 

注意:賦值器(setter)中,接收的值被自動命名為newValue。

willSet和didSet

EquilateralTriangle的構(gòu)造器進(jìn)行了如下操作:

  1. 為子類型的屬性賦值。
  2. 調(diào)用父類型的構(gòu)造器。
  3. 修改父類型的屬性。

如果不需要計算屬性的值,但需要在賦值前后進(jìn)行一些操作的話,使用willSet和didSet。

  1. class TriangleAndSquare { 
  2.     var triangle: EquilateralTriangle { 
  3.     willSet { 
  4.         square.sideLength = newValue.sideLength 
  5.     } 
  6.     } 
  7.     var square: Square { 
  8.     willSet { 
  9.         triangle.sideLength = newValue.sideLength 
  10.     } 
  11.     } 
  12.     init(size: Double, name: String) { 
  13.         square = Square(sideLength: size, name: name) 
  14.         triangle = EquilateralTriangle(sideLength: size, name: name) 
  15.     } 
  16. var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape"
  17. triangleAndSquare.square.sideLength 
  18. triangleAndSquare.square = Square(sideLength: 50, name: "larger square"
  19. triangleAndSquare.triangle.sideLength 

從而保證triangle和square擁有相等的sideLength。

調(diào)用方法

Swift中,函數(shù)的參數(shù)名稱只能在函數(shù)內(nèi)部使用,但方法的參數(shù)名稱除了在內(nèi)部使用外還可以在外部使用(第一個參數(shù)除外),例如:

  1. class Counter { 
  2.     var count: Int = 0 
  3.     func incrementBy(amount: Int, numberOfTimes times: Int) { 
  4.         count += amount * times 
  5.     } 
  6. var counter = Counter() 
  7. counter.incrementBy(2, numberOfTimes: 7) 

注意Swift支持為方法參數(shù)取別名:在上面的代碼里,numberOfTimes面向外部,times面向內(nèi)部。

?的另一種用途

使用可空值時,?可以出現(xiàn)在方法、屬性或下標(biāo)前面。如果?前的值為nil,那么?后面的表達(dá)式會被忽略,而原表達(dá)式直接返回nil,例如:

  1. let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional 
  2. square") 
  3. let sideLength = optionalSquare?.sideLength 

當(dāng)optionalSquare為nil時,sideLength屬性調(diào)用會被忽略。

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

枚舉

使用enum創(chuàng)建枚舉——注意Swift的枚舉可以關(guān)聯(lián)方法:

  1. enum Rank: Int { 
  2.     case Ace = 1 
  3.     case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten 
  4.     case Jack, Queen, King 
  5.         func simpleDescription() -> String { 
  6.         switch self { 
  7.             case .Ace: 
  8.                 return "ace" 
  9.             case .Jack: 
  10.                 return "jack" 
  11.             case .Queen: 
  12.                 return "queen" 
  13.             case .King: 
  14.                 return "king" 
  15.             default
  16.                 return String(self.toRaw()) 
  17.         } 
  18.     } 
  19. let ace = Rank.Ace 
  20. let aceRawValue = ace.toRaw() 

使用toRaw和fromRaw在原始(raw)數(shù)值和枚舉值之間進(jìn)行轉(zhuǎn)換:

  1. if let convertedRank = Rank.fromRaw(3) { 
  2.     let threeDescription = convertedRank.simpleDescription() 

注意枚舉中的成員值(member value)是實(shí)際的值(actual value),和原始值(raw value)沒有必然關(guān)聯(lián)。

一些情況下枚舉不存在有意義的原始值,這時可以直接忽略原始值:

  1. enum Suit { 
  2.     case Spades, Hearts, Diamonds, Clubs 
  3.         func simpleDescription() -> String { 
  4.         switch self { 
  5.             case .Spades: 
  6.                 return "spades" 
  7.             case .Hearts: 
  8.                 return "hearts" 
  9.             case .Diamonds: 
  10.                 return "diamonds" 
  11.             case .Clubs: 
  12.                 return "clubs" 
  13.         } 
  14.     } 
  15. let hearts = Suit.Hearts 
  16. let heartsDescription = hearts.simpleDescription() 

除了可以關(guān)聯(lián)方法,枚舉還支持在其成員上關(guān)聯(lián)值,同一枚舉的不同成員可以有不同的關(guān)聯(lián)的值:

  1. enum ServerResponse { 
  2.     case Result(String, String) 
  3.     case Error(String) 
  4.   
  5. let success = ServerResponse.Result("6:00 am""8:09 pm"
  6. let failure = ServerResponse.Error("Out of cheese."
  7.   
  8. switch success { 
  9.     case let .Result(sunrise, sunset): 
  10.         let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." 
  11.     case let .Error(error): 
  12.         let serverResponse = "Failure... \(error)" 

結(jié)構(gòu)

Swift使用struct關(guān)鍵字創(chuàng)建結(jié)構(gòu)。結(jié)構(gòu)支持構(gòu)造器和方法這些類的特性。結(jié)構(gòu)和類的最大區(qū)別在于:結(jié)構(gòu)的實(shí)例按值傳遞(passed by value),而類的實(shí)例按引用傳遞(passed by reference)。

  1. struct Card { 
  2.     var rank: Rank 
  3.     var suit: Suit 
  4.     func simpleDescription() -> String { 
  5.         return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" 
  6.     } 
  7. let threeOfSpades = Card(rank: .Three, suit: .Spades) 
  8. let threeOfSpadesDescription = threeOfSpades.simpleDescription() 

協(xié)議(protocol)和擴(kuò)展(extension)

協(xié)議

Swift使用protocol定義協(xié)議:

  1. protocol ExampleProtocol { 
  2.     var simpleDescription: String { get } 
  3.     mutating func adjust() 

類型、枚舉和結(jié)構(gòu)都可以實(shí)現(xiàn)(adopt)協(xié)議:

  1. class SimpleClass: ExampleProtocol { 
  2.     var simpleDescription: String = "A very simple class." 
  3.     var anotherProperty: Int = 69105 
  4.     func adjust() { 
  5.         simpleDescription += " Now 100% adjusted." 
  6.     } 
  7. var a = SimpleClass() 
  8. a.adjust() 
  9. let aDescription = a.simpleDescription 
  10.   
  11. struct SimpleStructure: ExampleProtocol { 
  12.     var simpleDescription: String = "A simple structure" 
  13.     mutating func adjust() { 
  14.         simpleDescription += " (adjusted)" 
  15.     } 
  16. var b = SimpleStructure() 
  17. b.adjust() 
  18. let bDescription = b.simpleDescription 

擴(kuò)展

擴(kuò)展用于在已有的類型上增加新的功能(比如新的方法或?qū)傩裕?,Swift使用extension聲明擴(kuò)展:

  1. extension Int: ExampleProtocol { 
  2.     var simpleDescription: String { 
  3.         return "The number \(self)" 
  4.     } 
  5.     mutating func adjust() { 
  6.         self += 42 
  7.     } 
  8. 7.simpleDescription 

泛型(generics)

Swift使用<>來聲明泛型函數(shù)或泛型類型:

  1. func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] { 
  2.     var result = ItemType[]() 
  3.     for i in 0..times { 
  4.         result += item 
  5.     } 
  6.     return result 
  7. repeat("knock", 4) 

Swift也支持在類、枚舉和結(jié)構(gòu)中使用泛型:

  1. // Reimplement the Swift standard library's optional type 
  2. enum OptionalValue<T> { 
  3.     case None 
  4.     case Some(T) 
  5. var possibleInteger: OptionalValue<Int> = .None 
  6. possibleInteger = .Some(100) 

有時需要對泛型做一些需求(requirements),比如需求某個泛型類型實(shí)現(xiàn)某個接口或繼承自某個特定類型、兩個泛型類型屬于同一個類型等等,Swift通過where描述這些需求:

  1. func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool { 
  2.     for lhsItem in lhs { 
  3.         for rhsItem in rhs { 
  4.             if lhsItem == rhsItem { 
  5.                 return true 
  6.             } 
  7.         } 
  8.     } 
  9.     return false 
  10. anyCommonElements([1, 2, 3], [3]) 

Swift語言概覽就到這里,有興趣的朋友請進(jìn)一步閱讀The Swift Programming Language。

接下來聊聊個人對Swift的一些感受。

個人感受

注意:下面的感受純屬個人意見,僅供參考。

大雜燴

盡管我接觸Swift不足兩小時,但很容易看出Swift吸收了大量其它編程語言中的元素,這些元素包括但不限于:

  1. 屬性(Property)、可空值(Nullable type)語法和泛型(Generic Type)語法源自C#。
  2. 格式風(fēng)格與Go相仿(沒有句末的分號,判斷條件不需要括號)。
  3. Python風(fēng)格的當(dāng)前實(shí)例引用語法(使用self)和列表字典聲明語法。
  4. Haskell風(fēng)格的區(qū)間聲明語法(比如1..3,1...3)。
  5. 協(xié)議和擴(kuò)展源自O(shè)bjective-C(自家產(chǎn)品隨便用)。
  6. 枚舉類型很像Java(可以擁有成員或方法)。
  7. class和struct的概念和C#極其相似。

注意這里不是說Swift是抄襲——實(shí)際上編程語言能玩的花樣基本就這些,況且Swift選的都是在我看來相當(dāng)不錯的特性。

而且,這個大雜燴有一個好處——就是任何其它編程語言的開發(fā)者都不會覺得Swift很陌生——這一點(diǎn)很重要。

拒絕隱式(Refuse implicity)

Swift去除了一些隱式操作,比如隱式類型轉(zhuǎn)換和隱式方法重載這兩個坑,干的漂亮。

Swift的應(yīng)用方向

我認(rèn)為Swift主要有下面這兩個應(yīng)用方向:

教育

我指的是編程教育。現(xiàn)有編程語言最大的問題就是交互性奇差,從而導(dǎo)致學(xué)習(xí)曲線陡峭。相信Swift及其交互性極強(qiáng)的編程環(huán)境能夠打破這個局面,讓更多的人——尤其是青少年,學(xué)會編程。

這里有必要再次提到Brec VictorInventing on Principle,看了這個視頻你就會明白一個交互性強(qiáng)的編程環(huán)境能夠帶來什么。

應(yīng)用開發(fā)

現(xiàn)有的iOS和OS X應(yīng)用開發(fā)均使用Objective-C,而Objective-C是一門及其繁瑣(verbose)且學(xué)習(xí)曲線比較陡峭的語言,如果Swift能夠提供 一個同現(xiàn)有Obj-C框架的簡易互操作接口,我相信會有大量的程序員轉(zhuǎn)投Swift;與此同時,Swift簡易的語法也會帶來相當(dāng)數(shù)量的其它平臺開發(fā)者。

總之,上一次某家大公司大張旗鼓的推出一門編程語言及其編程平臺還是在2000年(微軟推出C#),將近15年之后,蘋果推出Swift——作為開發(fā)者,我很高興能夠見證一門編程語言的誕生。

原文出處: Lucia(@peng_gong)

責(zé)任編輯:閆佳明 來源: zh.lucida.me
相關(guān)推薦

2014-06-03 10:44:20

Swift開發(fā)語言

2014-07-08 10:29:12

Swift

2014-07-16 09:41:12

Swift傳統(tǒng)編程

2015-12-04 10:05:09

蘋果編程開源

2015-04-14 14:23:38

蘋果Swift編程語言

2014-06-10 11:06:54

技術(shù)周刊

2018-04-30 18:07:51

谷歌開源編程

2015-10-19 09:23:44

新編編程女人

2014-06-06 09:13:28

SwiftSwift編程

2014-06-04 10:42:34

Swift蘋果iOS

2012-03-05 13:08:35

編程

2015-12-25 15:52:50

Linux蘋果編程Swift

2021-04-13 10:14:12

編程語言PythonJava

2014-06-16 10:02:42

SwiftiOSWWDC

2012-02-17 09:33:08

KotlinJavaJVM

2016-04-08 10:29:46

androidswiftjava

2011-10-13 10:07:26

Dart

2014-07-16 15:10:42

Swift編程語言

2014-07-17 10:12:58

Swift

2016-01-04 13:52:12

UbuntuSwift安裝
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號