Calling Types As Functions
讓一般的物件可以像函數一樣,只要給它一些參數,它就可以回傳一些別的東西,用法類似 subscript,只是把 instance[index] 改為 instance(index) 而已。
struct Adder {
var base: Int
// ⭐️ callAsFunction
func callAsFunction(_ x: Int) -> Int {
return base + x
}
}let add3 = Adder(base: 3)
add3(10) // 13 == adder.callAsFunction(10)Last updated