📂
CMiOSBook
  • CMoney iOS Book
  • Coding 101
    • Value / Reference Type
    • ARC + Retain Cycle
    • 物件之間的溝通方式
  • 工具主題
    • 基本工具篇
    • Git 篇
  • 架構主題
    • MVC
  • CodingStyle主題
    • CodingStyle 規則
      • 專案(Project)
      • 命名(Naming)
      • 程式格式(Format)
      • 註解(Comment)
      • 類別與結構(Classes and Structures)
      • 修飾詞(Modifier)
      • 閉包表達式(Closures)
    • 靜態檢查器
    • 專案基本規定
  • UI主題
    • UIScrollViewDelegate & UITableViewDelegate
  • Charts主題
    • 簡介
    • Lesson1 Chart Setup
    • Lesson2 Chart Data
    • Lesson3 CombinedChartView
    • Lesson4 Renderer
  • Test主題
    • 單元測試的基本概念
    • XCTest-UnitTest
    • XCTest-UITest
  • 學習資源
    • 相關網站
    • 相關會議與社群
    • 計算機考題
Powered by GitBook
On this page

Was this helpful?

  1. CodingStyle主題
  2. CodingStyle 規則

閉包表達式(Closures)

Closure當作一個沒有名稱的Function,所以Closure一樣可以定義一段程式碼的區塊,也可以接受參數與回傳資料

///這是Function
func 方法名(參數1, 參數2) -> 回傳型別{
    程式碼區塊
}

///這是Closure
{ (參數1, 參數2) -> 回傳型別 in
    程式碼區塊
}
/// 宣告帶有Closure參數的方法
func getMemberBonus(completionHandler: ((Int)->Void)?){
    if let bonus = bonus{
        completionHandler?(bonus)
    }
}

/// 呼叫方法範例1 <--- 一般的寫法
getMemberBonus(completionHandler: {
    bonus in 
    printf("我有\(bonus)購物金")
})

/// 呼叫方法範例2 <--- TrailingClosure寫法
getMemberBonus{ bonus in 
    printf("我有\(bonus)購物金")
}

如果單一Closure當結尾參數時,請使用TrailingClosure

如果多個Closure當結尾參數時,請分開並完整寫出、禁止使用TrailingClosure

//單一Closure當結尾參數 - 使用TrailingClosure
UIView.animateWithDuration(1.0) {
  self.myView.alpha = 0
}

//多個Closure當結尾參數 - 禁止使用TrailingClosure
UIView.animateWithDuration(1.0,
  animations: {
    self.myView.alpha = 0
  },
  completion: { finished in
    self.myView.removeFromSuperview()
  }
)

Previous修飾詞(Modifier)Next靜態檢查器

Last updated 4 years ago

Was this helpful?