swift語言學習相關教程 蘋果swift程式設計語言基礎相關教程

來源:互聯網
上載者:User

  swift語言學習教程,幫客之家小編胖胖帶來了蘋果swift程式設計語言基礎教程,對於蘋果發布的這款程式設計語言很多朋友可能不是很瞭解,沒關係,下文將會詳細介紹這款語言的基礎代碼,一起來瞭解吧~


  --基本概念

  註:這一節的代碼源自The Swift Programming Language中的A Swift Tour。

  --Hello, world

  類似於指令碼語言,下面的代碼即是一個完整的Swift程式。

  ◾println("Hello, world") 變數與常量

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

  ◾var myVariable = 42

  ◾myVariable = 50

  ◾let myConstant = 42

  --類型推導

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

  ◾let explicitDouble : Double = 70

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

  ◾let label = "The width is "

  ◾let width = 94

  ◾let width = label + String(width)

  --字串格式化

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

  ◾let apples = 3

  ◾let oranges = 5

  ◾let appleSummary = "I have \(apples) apples."

  ◾let appleSummary = "I have \(apples + oranges) pieces of fruit."

  --數組和字典

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

  ◾var shoppingList = ["catfish", "water", "tulips", "blue paint"]

  ◾shoppingList[1] = "bottle of water"

  ◾var occupations = [

  ◾ "Malcolm": "Captain",

  ◾ "Kaylee": "Mechanic",

  ◾]

  ◾occupations["Jayne"] = "Public Relations"

  一般使用初始化器(initializer)文法建立空數組和空字典:

  ◾ let emptyArray = String[]()

  ◾ let emptyDictionary = Dictionary()

  如果類型資訊已知,則可以使用[]聲明空數組,使用[:]聲明空字典。

  --控制流程

  概覽

  Swift的條件陳述式包含if和switch,迴圈語句包含for-in、for、while和do-while,迴圈/判斷條件不需要括弧,但迴圈/判斷體(body)必需括弧:

  ◾let individualScores = [75, 43, 103, 87, 12]

  var teamScore = 0

  for score in individualScores {

  if score > 50 {

  teamScore += 3

  } else {

  teamScore += 1

  }

  }

  可空類型

  結合if和let,可以方便的處理可空變數(nullable variable)。對於空值,需要在型別宣告後添加?顯式標明該類型可空。

  ◾var optionalString: String? = "Hello"

  optionalString == nil

  var optionalName: String? = "John Appleseed"

  var gretting = "Hello!"

  if let name = optionalName {

  gretting = "Hello, \(name)"

  }

  靈活的switch

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

  ◾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除了遍曆數組也可以用來遍曆字典:

  ◾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迴圈:

  ◾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實現同樣的邏輯。

  ◾var firstForLoop = 0

  ◾for i in 0..3 {

  ◾ firstForLoop += i

  ◾}

  ◾firstForLoop

  ◾var secondForLoop = 0

  ◾for var i = 0; i < 3; ++i {

  ◾ secondForLoop += 1

  ◾}

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

  --函數和閉包

  函數

  Swift使用func關鍵字聲明函數:

  ◾func greet(name: String, day: String) -> String {

  ◾ return "Hello \(name), today is \(day)."

  ◾}

  ◾greet("Bob", "Tuesday")

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

  ◾func getGasPrices() -> (Double, Double, Double) {

  ◾ return (3.59, 3.69, 3.79)

  ◾}

  ◾getGasPrices()

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

  ◾func sumOf(numbers: Int...) -> Int {

  ◾ var sum = 0

  ◾ for number in numbers {

  ◾ sum += number

  ◾ }

  ◾ return sum

  ◾}

  ◾sumOf()

  ◾sumOf(42, 597, 12)

  函數也可以嵌套函數:

  ◾func returnFifteen() -> Int {

  ◾ var y = 10

  ◾ func add() {

  ◾ y += 5

  ◾ }

  ◾ add()

  ◾ return y

  ◾}

  ◾returnFifteen()

  作為頭等對象,函數既可以作為傳回值,也可以作為參數傳遞:

  ◾func makeIncrementer() -> (Int -> Int) {

  ◾ func addOne(number: Int) -> Int {

  ◾ return 1 + number

  ◾ }

  ◾ return addOne

  ◾}

  ◾var increment = makeIncrementer()

  ◾increment(7)

  ◾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中可以利用{}聲明匿名閉包:

  ◾numbers.map({

  ◾ (number: Int) -> Int in

  ◾ let result = 3 * number

  ◾ return result

  ◾ })

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

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

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

  ◾sort([1, 5, 3, 12, 2]) { $0 > $1 } 類和對象 建立和使用類

  Swift使用class建立一個類,類可以包含欄位和方法:

  ◾class Shape {

  ◾var numberOfSides = 0

  ◾func simpleDescription() -> String {

  ◾return "A shape with \(numberOfSides) sides."

  ◾}

  ◾}

  建立Shape類的執行個體,並調用其欄位和方法。

  ◾var shape = Shape()

  ◾shape.numberOfSides = 7

  ◾varshapeDescription = shape.simpleDescription()

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

  ◾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父類方法):

  ◾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語言學習教程--屬性


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

  ◾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的構造器進行了如下操作:

  為子類型的屬性賦值。 調用父類型的構造器。 修改父類型的屬性。

  如果不需要計算屬性的值,但需要在賦值前後進行一些操作的話,使用willSet和didSet:

  ◾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

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

  --調用方法

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

  ◾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,例如:

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

  ◾square")

  ◾let sideLength = optionalSquare?.sideLength

  當optionalSquare為nil時,sideLength屬性調用會被忽略。

  --枚舉和結構

  枚舉

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

  ◾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()

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

  ◾if let convertedRank = Rank.fromRaw(3) {

  ◾let threeDescription = convertedRank.simpleDescription()

  ◾}

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

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

  ◾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()

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

  ◾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使用struct關鍵字建立結構。結構支援構造器和方法這些類的特性。結構和類的最大區別在於:結構的執行個體按值傳遞(passed by value),而類的執行個體按引用傳遞(passed by reference)。

  ◾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定義協議:

  ◾protocol ExampleProtocol {

  ◾ var simpleDescription: String { get }

  ◾ mutating func adjust()

  ◾}

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

  ◾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聲明擴充:

  ◾extension Int: ExampleProtocol {

  ◾ var simpleDescription: String {

  ◾ return "The number \(self)"

  ◾ }

  ◾ mutating func adjust() {

  ◾ self += 42

  ◾ }

  ◾}

  ◾7.simpleDescription

  泛型(generics)

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

  ◾func repeat(item: ItemType, times: Int) -> ItemType[] {

  ◾ var result = ItemType[]()

  ◾ for i in 0..times {

  ◾ result += item

  ◾ }

  ◾ return result

  ◾}

  ◾repeat("knock", 4)

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

  ◾// Reimplement the Swift standard library's optional type

  ◾enum OptionalValue {

  ◾ case None

  ◾ case Some(T)

  ◾}

  ◾var possibleInteger: OptionalValue = .None

  ◾possibleInteger = .Some(100)

  有時需要對泛型做一些需求(requirements),比如需求某個泛型型別實現某個介面或繼承自某個特定類型、兩個泛型型別屬於同一個類型等等,Swift通過where描述這些需求:

  ◾func anyCommonElements

  ◾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語言學習教程就到這裡啦~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.