Search code examples
swiftxcoderuntime-errorclosuresfunc

expression failed to parse, unknown error


I am writing a function that takes two parameters, one integer and one closure. It calls the closure the integers value times.

This is my code

func repeatTask(times: Int, task: () -> Void) {
    for _ in 0 ..< times {
        task
    }
}

let voidClosure: () -> Void = {
    print("Swift Apprentice is awesome!")
}

repeatTask(times: 5, task: voidClosure) 

The compiler gives me the following error:

expression failed to parse, unknown error

What's wrong here?


Solution

  • You're missing a () after the task.

    for _ in 0 ..< times {
        task()
    }
    

    Sometimes the compiler gives unhelpful errors, especially in Swift Playgrounds. In that case, I usually try an online sandbox like this one.