LoginSignup
1
2

More than 5 years have passed since last update.

Closuresって何?使い方は。

Posted at

参考にしたものは以下。公式のドキュメントです。
the swift programming language
swift 5

簡単にまとめておきたいと思います。

・基本的にはNestした関数。2重の関数。
・関数を完結に記述できる。
・変数を保持できる。

の3点かなと思います。


let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backward(_ s1: String, _ s2: String) -> Bool {
    return s1 > s2
}

//Nestした関数。

var reversedNames = names.sorted(by: backward)
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]

これを、ひとまとまりに。


reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    return s1 > s2
})

そして、単純、簡潔に、

reversedNames = n
ames.sorted(by: { $0 > $1 } )

もっと

reversedNames = names.sorted(by: >)

少し違う書き方もできる。これをTrailing Closuresという。

reversedNames = names.sorted() { $0 > $1 }

最後にもう一つ。変数を保持するタイプです。Capturing Values

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}
1
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
1
2