o1xhack
o1xhack

Reputation: 97

swift repeat func: expected identifier in function declaration

I'm using a Swift learning book about extensions with a closure as a parameter.

In the book, it told me

extension Int {
    func repeat(work: () -> ()) {
        for _ in 0..<self {
            work()
        }
    }
}

On the line

func repeat(work: () -> ()) {

Xcode tells me

Expected identifier in function declaration


and on the line:

for _ in 0..< self {

Xcode tells me

Braced block of statements is an unused closure

and

Expected ‘{’ to start the body of for-each loop


Can anyone can tell me why these errors occur and what should I do?

Upvotes: 0

Views: 1764

Answers (2)

Joey Yi Zhao
Joey Yi Zhao

Reputation: 42500

repeat is a keyword you can't use as a function name. Rename it to something else:

extension Int {
    func repeat1(work: () -> ()) {
        for _ in 0..<self {
            work()
        }
    }
}

Upvotes: 1

paulvs
paulvs

Reputation: 12053

There are a number of problems with the posted code:

  1. extensionInt should be extension Int, although I suspect this is a typo in you post
  2. As @Zhao Yi pointed out, repeat is a Swift keyword, you need to rename your function (e.g. repeatWork)
  3. The Swift Half-Open Range Operator requires either an empty space on both sides, or no space on both sides. Both these are valid:

    0 ..< self
    0..<self
    

Finally, you can call this function like this:

2.repeatWork({
    print("Hello")
})

or this:

2.repeatWork {
    print("Hola")
}

Upvotes: 1

Related Questions