3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】特殊な関数な使い方ができるcallAsFunctionについて

Posted at

はじめに

callAsFunctionという特殊な使い方ができる関数があると知りました。
私が最初にcallAsFunctionの存在に気づいたのはdismissででした。

@Environment(\.dismiss) var dismiss

// 同じことをしている
dismiss()
dismiss.callAsFunction()

実装方法

callAsFunctionという関数名で実装をすると、使用時に関数名なしで使用できます。

class Adder {
    func callAsFunction(_ a: Int, _ b: Int) -> Int {
        return a + b
    }
}

let adder = Adder()
let result1 = adder(1, 1) // 2
let result2 = adder(2, 3) // 5
let result3 = adder(4, 6) // 10
let result4 = adder(7, 5) // 12

おわり

構造体名で処理を表すことができるものであれば、callAsFunctionを使ったほうが良さそうですね!

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?