8
6

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 5 years have passed since last update.

Swift で "関数を返す関数" を定義する

Posted at

Swift では(例えば JavaScript のように)関数はオブジェクトとして扱えるので、次のように関数を返す関数、というのも定義できる。

手元の Swift のバージョン:1.1

func makeCounter() -> (Void -> Int) {

  var n:Int = 1

  return { () -> Int in
    return n++
  }
}

var count = makeCounter()

println(count()) // => 1
println(count()) // => 2
println(count()) // => 3
println(count()) // => 4

ちなみに { (引数) -> 戻り値の型 in 処理内容 } は無名関数のようなもの(Swift ではクロージャと呼ばれている模様)

また1行目の (Void -> Int) は「引数なし(Void)で戻り値の型Intの関数」を、関数 makeCounter の戻り値の型とする、という意味。説明がややこしいですが..

8
6
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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?