I saw a dictionary data, its value is like:

var myDict=["name": "John","age": 28]

I see a code like below:

myDict.flatMap {let a=$0.0let b=$0.1...}

What does $0.0 mean? What does $0.1 mean? What is the difference between $0 and $0.1?

  • Show the code where a and b variables are used.– kiranderSep 28 '17 at 13:28

$0 is a shorthand name for first argument passed to closure. In this case, as you're mapping a Dictionary, that argument is a tuple - hence $0.0 is a key, and $0.1 is a value

For more info on shorthand argument names, see Swift documentation on closures

  • 3
    For better readability you should use $0.key for the key and $0.value for the value.– Leo DabusSep 28 '17 at 13:34
  • 4
    Or flatMap { (key, value) in ... }– Martin RSep 28 '17 at 13:37
  • Also parentheses it is not needed key, value in– Leo DabusSep 28 '17 at 13:39
  • Why do you say argument is a tuple? Isn't tuple value comma separated e.g. (3,4)? Dictionary's mapping argument is colon separated e.g. ("name":"John"). Are you saying tuple could also be colon separated e.g. (3:4)?– Leem.finSep 28 '17 at 22:19

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.