-2
struct Parser<A> {
    let parse: (String) -> (A,String)?
}

func character(condition:@escaping (Character) -> Bool) -> Parser<Character> {
    return Parser(parse: {str in
        guard let char = str.first, condition(char) else {
            return nil
        }
        return (char,String(str.dropFirst()))
    })
}

In the code above, I have hard time figuring out what happens. More specific, what does

let char = str.first, condition(char)

do? Is this even a legal construct? The code compiles so it must be, but what is happening? let char = str.first is an assignment and condition(char) is a boolean. How can you have an assignment followed by a comma, followed by something that evaluates to a boolean.

Bob Ueland
  • 1,804
  • 1
  • 15
  • 24

1 Answers1

1

More specific, what does

   let char = str.first, condition(char)

do?

Nothing. There is no such expression in your code.

What’s there is this:

guard let char = str.first, condition(char)

That guard makes all the difference. The comma joins two conditions as by nesting, so we have, in effect (since guard is a form of if):

if let char = str.first

and

if condition(char)

You understand both of those well enough, surely? If not, the only remaining thing that might be unfamiliar to you is if let, which is extremely fundamental to Swift and easy to learn about; it unwraps the Optional safely, avoiding the danger of crashing thru an attempt to unwrap nil.

Community
  • 1
  • 1
matt
  • 515,959
  • 87
  • 875
  • 1,141