Calling Types As Functions
讓一般的物件可以像函數一樣,只要給它一些參數,它就可以回傳一些別的東西,用法類似 subscript,只是把 instance[index] 改為 instance(index) 而已。
This feature supports argument labels and parameter types, throws and rethrows, and is not constrained to primary type declarations. Furthermore, it is possible to define multiple callAsFunction methods on a single type, and Swift will handle which one to call, similar to a simple overloading.
struct Adder {
var base: Int
// ⭐️ callAsFunction
func callAsFunction(_ x: Int) -> Int {
return base + x
}
}
#todo: #if swift>=5.2 寫入 CGRect(x, y)
Last updated
Was this helpful?