利用 typealias 幫 function 型別取名

撰寫 Swift 程式時,我們有時會宣告 function 型別的變數或參數來儲存 function 或 closure,比方以下例子:

  • 變數 buyBook2 是 function 型別
func buyBook(name: String, author: String) -> String {
return "買了\(author)的\(name)"
}
var buyBook2: (String, String) -> String = buyBook
  • 參數 sport 是 function 型別
func eatAndExercise(sport: () -> String) -> String {
var message = "大吃特吃後"
for _ in 1...10 {
message += sport()
}
return message
}

func playTableTennis() -> String {
"打桌球"
}

eatAndExercise(sport: playTableTennis)

不過 function 型別寫起來有點複雜,要寫 ( ),參數型別,->,回傳型別,因此如果想偷懶的話,我們可以用 typealias 幫 function 型別取名,方便之後使用。

接下來讓我們看看以下 Apple 官方使用 typealias 幫 function 型別取名的例子吧。

Fruta: Building a Feature-Rich App with SwiftUI

利用 typealias 幫 function 型別取名 FetchCompletionHandler & PurchaseCompletionHandler。

typealias FetchCompletionHandler = (([SKProduct]) -> Void)
typealias PurchaseCompletionHandler = ((SKPaymentTransaction?) -> Void)
// MARK: - Store
class Store: NSObject, ObservableObject {

宣告 property fetchCompletionHandler & purchaseCompletionHandler,指定型別為 FetchCompletionHandler? & PurchaseCompletionHandler? 。

class Store: NSObject, ObservableObject {
private var fetchCompletionHandler: FetchCompletionHandler?
private var purchaseCompletionHandler: PurchaseCompletionHandler?

利用 FetchCompletionHandler & PurchaseCompletionHandler 指定參數的型別

extension Store {
private func buy(_ product: SKProduct, completion: @escaping PurchaseCompletionHandler) {
// Save our completion handler for later
purchaseCompletionHandler = completion

// Create the payment and add it to the queue
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}


private func fetchProducts(_ completion: @escaping FetchCompletionHandler) {
guard self.productsRequest == nil else {
return
}
// Store our completion handler for later
fetchCompletionHandler = completion

// Create and start this product request
productsRequest = SKProductsRequest(productIdentifiers: allProductIdentifiers)
productsRequest?.delegate = self
productsRequest?.start()
}

呼叫 fetchCompletionHandler & purchaseCompletionHandler 的程式碼片段。

  • 呼叫 fetchCompletionHandler。
DispatchQueue.main.async {
self.fetchCompletionHandler?(loadedProducts)
self.fetchCompletionHandler = nil
self.productsRequest = nil
}
  • 呼叫 purchaseCompletionHandler。
if shouldFinishTransaction {

SKPaymentQueue.default().finishTransaction(transaction)
DispatchQueue.main.async {
self.purchaseCompletionHandler?(transaction)
self.purchaseCompletionHandler = nil
}
}

其它例子: Today App,UIKit

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com