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
    }
}

從這個語法看起來,這個就有點像 subscript 一樣,只是把 subscript 的 something[index] 改為 something(index) 而已。

#todo: #if swift>=5.2 寫入 CGRect(x, y)

Last updated