0

The book Swift Coding Challenges has the following problem:

"Write a function that accepts a string, and returns how many times a specific character appears, taking case into account."

In one of the solutions

func challenge5b(input: String, count: Character) -> Int {
    return input.reduce(0) {
        $1 == count ? $0 + 1 : $0
    }
}

It's not clear to me where$0 and $1 come from. How exactly does the reduce function work when stepping through the input string?

Jakory
  • 23
  • 4
  • See _Shorthand Argument Names_ section in [Swift Programming Language: Closures](https://docs.swift.org/swift-book/LanguageGuide/Closures.html#ID95). – Rob Mar 29 '22 at 00:55
  • It is equivalent to `return input.reduce(0) { result, character in character == count ? result + 1 : result }`. As an aside, I think the choice of `count` for that second parameter name is not a very good choice. – Rob Mar 29 '22 at 00:59

0 Answers0