Learn Courses My Dashboard

Module 4 WrappeUp Challenge

Hi! guys i just cant understand this this part of the code from the solution upon going back to the module where firstIndex was topic it is used differently there, I just don’t underst what $0.id means I know the dolloar sign is for binding but where the 0 come from? In addition does the .toggle() changes the value of the boolean stored in dataBook.isFavouriite?

$ does not indicate a binding in this instance. $0 indicates the first argument passed to a closure. (Likewise, $1 is the second argument, $2 is the third, etc.)

Closures can take named arguments, like this:

dataBook.firstIndex(where: { value in 
    value.id == forId

or you can use shorthand argument labels like $0, $1 and so on:

dataBook.firstIndex(where: {
    $0.id == forId

dataBook.firstIndex(where: {$0.id == forId}) is just the latter form condensed to a single line.


In answer to your last question:

Yes it does. If it is currently true then the .toggle() changes it to false and if it is false changes it to true.

1 Like

Thanks for the elaboration sir @roosterboy sir may I ask when to use $1, $2…and so on i try changing the $0 to $1 and i get an error sir.

I was having trouble to change the value of isFavourite I cant express it on if statement, toggle() is the key hahaha thank you sir @Chris_Parker

What I mean sir to fully understand the use of $0, $1… and so on when should I used $0 or $1 sir?

Right, you can’t do that because firstIndex(where:) takes a closure that has one parameter. So $0 references that single parameter. $1 would refernce the second parameter but there is no second parameter so you get an error instead.

When you have a closure and don’t want to name its parameters. So like in the examples I gave earlier, you can either name the parameter passed into the closure you supplied to firstIndex(where:) or you can use the $0 shorthand.

Shorthand parameters are very useful with map, filter, etc. IOW, where you supply a closure that is usually short and simple. Other such methods could be contains(where:), sorted(by:), and allSatisfy(_:) called on an array. Those often aren’t closures that involves a lot of logic and many times can be written inline, as in the firstIndex(where:) function from your original post, and it doesn’t make a lot of sense to use a fullblown name for the parameter(s).

But ultimately, it comes down to coding style and personal choice. You don’t have to use shortcut arguments, but the option is there.

1 Like