Module 4 : Wrap Up! (part 3)

The Challenge so Far

Continuing the Book Library wrap-up challenge, trying to get over the latest hurdle:

  1. Debugging – trying to figure out why my code that looks okay doesn’t want to show much other than the title. Must be something wrong with the JSON or the decoding.
    • If I change my personalised JSON file back to the original, the preview is working. Wonder what the difference is? Must find out if I don’t want to run into this problem in the future.
    • Solution: Those annoying quotes that needed escaping. One well, it escaped the escaping.
    • Now, back to the challenge…
  2. The provided solution uses $0, which I’ve encountered in other languages but can’t see what it does here so I’m off to do some Googling.
    • Okay, figured it out. It’s shorthand, which is fine if you know what it’s shorthand for but, in what is supposed to be a lesson, some additional guidance would have been helpful.
if let a = b.firstIndex(where: { c in
    c.id == Id
}) {
    // some action
}

Shorthand version would replace c (first argument) with $0, re:

if let a = b.firstIndex(where: { 
    $0.id == Id 
}) {
    // some action
}

This can be further reduced to:

if let a = b.firstIndex(where: {$0.id == Id}) {
    // some action
}

This code finds the firstIndex in b where the condition (c.id equals Id) is true, and assigns that index value to a. If it doesn’t find a match then // some action is not executed.

More to follow...