1
1

More than 1 year has passed since last update.

【Swift】$0ってなに???

Posted at

はじめに

こんな感じで当たり前のように出てくる$0はなんなのでしょうか

answers.map { $0.text }

ついさっき理解した(たぶん)ので記事にしときます!

$0の正体

結論
クロージャの省略記法
$0は引数の1つ目
$1は引数の2つ目


例えば?

このようなクロージャがあったとします。

func test(callback: (Int) -> Void) {
    callback(1)
}

通常の場合はこのようになります。

test { int in
    print(int)
}

これを省略記法を使用して書くとこのようになります。

test {
    print($0)
}

かんたん!!

おわり

この記法がよく使われているmap, filter, reduceとかはなんか難しそうで避けてました笑
でも理解したら意外と簡単でびっくり!!
これからは使っていこうと思います!!

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