iOS開發- 速學Swift-中文概述

Swift是什麼?

Swift是蘋果於WWDC 2014公佈的編程語言,這裏引用The Swift Programming Language的原話:css

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.html

Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible and more fun.web

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.express

Swift is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.編程

簡單的說:swift

  1. Swift用來寫iOS和OS X程序。(預計也不會支持其餘屌絲系統)
  2. Swift吸收了C和Objective-C的優勢,且更增強大易用。
  3. Swift可以使用現有的Cocoa和Cocoa Touch框架。

  4. Swift兼具編譯語言的高性能(Performance)和腳本語言的交互性(Interactive)。

Swift語言概覽

基本概念

注:這一節的代碼源自The Swift Programming Language中的A Swift Tourvim

Hello, world

相似於腳本語言,如下的代碼便是一個完整的Swift程序。數組

1
println("Hello, world") 

變量與常量

Swift使用var聲明變量。let聲明常量。閉包

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

類型推導

Swift支持類型推導(Type Inference),因此上面的代碼不需指定類型,假設需要指定類型:app

1
let explicitDouble : Double = 70 

Swift不支持隱式類型轉換(Implicitly casting),因此如下的代碼需要顯式類型轉換(Explicitly casting):

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

字符串格式化

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

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

數組和字典

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

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

通常使用初始化器(initializer)語法建立空數組和空字典:

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

假設類型信息已知。則可以使用[]聲明空數組,使用[:]聲明空字典。

控制流

概覽

Swift的條件語句包括ifswitch,循環語句包括for-inforwhiledo-while,循環/推斷條件不需要括號,但循環/推斷體(body)必需括號:

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

可空類型

結合iflet,可以方便的處理可空變量(nullable variable)。

對於空值,需要在類型聲明後加入?

顯式標明該類型可空。

1
2
3
4
5
6
7
8

var optionalString: String?

= "Hello" optionalString == nil var optionalName: String? = "John Appleseed" var gretting = "Hello!" if let name = optionalName { gretting = "Hello, \(name)" }

靈活的switch

Swift中的switch支持各類各樣的比較操做:

1
2
3
4
5
6
7
8
9
10
11

let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?

" default: let vegetableComment = "Everything tastes good in soup." }

其餘循環

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

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

while循環和do-while循環:

1
2
3
4
5
6
7
8
9
10
11
var n = 2 while n < 100 {  n = n * 2 } n  var m = 2 do {  m = m * 2 } while m < 100 m 

Swift支持傳統的for循環,此外也可以經過結合..(生成一個區間)和for-in實現相同的邏輯。

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

注意:Swift除了..還有.....生成前閉後開的區間。而...生成前閉後閉的區間。

函數和閉包

函數

Swift使用funckeyword聲明函數:

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

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

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

支持帶有變長參數的函數:

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

函數也可以嵌套函數:

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

做爲頭等對象。函數既可以做爲返回值。也可以做爲參數傳遞:

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

閉包

本質來講,函數是特殊的閉包,Swift中可以利用{}聲明匿名閉包:

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

當閉包的類型已知時,可以使用如下的簡化寫法:

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

此外還可以經過參數的位置來使用參數,當函數最後一個參數是閉包時,可以使用如下的語法:

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

類和對象

建立和使用類

Swift使用class建立一個類,類可以包括字段和方法:

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

建立Shape類的實例,並調用其字段和方法。

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

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

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

使用deinit進行清理工做。

繼承和多態

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

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

注意:假設這裏的simpleDescription方法沒有被標識爲override。則會引起編譯錯誤。

屬性

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

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

注意:賦值器(setter)中,接收的值被本身主動命名爲newValue

willSet和didSet

EquilateralTriangle的構造器進行了例如如下操做:

  1. 爲子類型的屬性賦值。
  2. 調用父類型的構造器。
  3. 改動父類型的屬性。

假設不需要計算屬性的值。但需要在賦值先後進行一些操做的話,使用willSetdidSet

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

從而保證trianglesquare擁有相等的sideLength

調用方法

Swift中,函數的參數名稱僅僅能在函數內部使用,但方法的參數名稱除了在內部使用外還可以在外部使用(第一個參數除外),好比:

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

注意Swift支持爲方法參數取別名:在上面的代碼裏。numberOfTimes面向外部。times面向內部。

?的還有一種用途

使用可空值時。?

可以出現在方法、屬性或下標前面。

假設?前的值爲nil,那麼?後面的表達式會被忽略。而原表達式直接返回nil,好比:

1
2
3

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?

.sideLength

optionalSquarenil時。sideLength屬性調用會被忽略。

枚舉和結構

枚舉

使用enum建立枚舉——注意Swift的枚舉可以關聯方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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.toRaw())  }  } } let ace = Rank.Ace let aceRawValue = ace.toRaw() 

使用toRawfromRaw在原始(raw)數值和枚舉值之間進行轉換:

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

注意枚舉中的成員值(member value)是實際的值(actual value)。和原始值(raw value)沒有一定關聯。

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

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

除了可以關聯方法,枚舉還支持在其成員上關聯值。同一枚舉的不一樣成員可以有不一樣的關聯的值:

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

結構

Swift使用structkeyword建立結構。

結構支持構造器和方法這些類的特性。

結構和類的最大差異在於:結構的實例按值傳遞(passed by value)。而類的實例按引用傳遞(passed by reference)。

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

協議(protocol)和擴展(extension)

協議

Swift使用protocol定義協議:

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

類型、枚舉和結構都可以實現(adopt)協議:

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

擴展

擴展用於在已有的類型上添加新的功能(比方新的方法或屬性)。Swift使用extension聲明擴展:

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

泛型(generics)

Swift使用<>來聲明泛型函數或泛型類型:

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

Swift也支持在類、枚舉和結構中使用泛型:

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

有時需要對泛型作一些需求(requirements),比方需求某個泛型類型實現某個接口或繼承自某個特定類型、兩個泛型類型屬於同一個類型等等,Swift經過where描寫敘述這些需求:

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

Swift語言概覽就到這裏,有興趣的朋友請進一步閱讀The Swift Programming Language

接下來聊聊我的對Swift的一些感覺。

我的感覺

注意:如下的感覺純屬我的意見。僅供參考。

大雜燴

雖然我接觸Swift不足兩小時。但很是easy看出Swift吸取了大量其餘編程語言中的元素,這些元素包括但不限於:

  1. 屬性(Property)、可空值(Nullable type)語法和泛型(Generic Type)語法源自C#。
  2. 格式風格與Go相仿(沒有句末的分號。推斷條件不需要括號)。

  3. Python風格的當前實例引用語法(使用self)和列表字典聲明語法。
  4. Haskell風格的區間聲明語法(比方1..31...3)。
  5. 協議和擴展源自Objective-C(自家產品隨便用)。
  6. 枚舉類型很是像Java(可以擁有成員或方法)。
  7. classstruct的概念和C#極其相似。

注意這裏不是說Swift是抄襲——實際上編程語言能玩的花樣基本就這些,何況Swift選的都是在我看來至關不錯的特性。

而且。這個大雜燴有一個優勢——就是不論什麼其餘編程語言的開發人員都不會以爲Swift很是陌生——這一點很是重要。

拒絕隱式(Refuse implicity)

Swift去除了一些隱式操做,比方隱式類型轉換和隱式方法重載這兩個坑,乾的美麗。

Swift的應用方向

我以爲Swift主要有如下這兩個應用方向:

教育

我指的是編程教育。現有編程語言最大的問題就是交互性奇差,從而致使學習曲線陡峭。相信Swift及其交互性極強的編程環境可以打破這個局面,讓不少其餘的人——尤爲是青少年。學會編程。

這裏有必要再次提到Brec VictorInventing on Principle。看了這個視頻你就會明確一個交互性強的編程環境可以帶來什麼。

應用開發

現有的iOS和OS X應用開發均使用Objective-C,而Objective-C是一門及其繁瑣(verbose)且學習曲線比較陡峭的語言,假設Swift可以提供一個同現有Obj-C框架的簡易互操做接口,我相信會有大量的程序猿轉投Swift;與此同一時候,Swift簡易的語法也會帶來至關數量的其餘平臺開發人員。

總之,上一次某家大公司大張旗鼓的推出一門編程語言及其編程平臺仍是在2000年(微軟推出C#),將近15年以後。蘋果推出Swift——做爲開發人員。我很是高興可以見證一門編程語言的誕生。


原文連接:http://zh.lucida.me/blog/an-introduction-to-swift/
相關文章
相關標籤/搜索