jjaeko
jjaeko

Reputation: 235

What () -> () means in swift?

extension Int {
    func repetitions(task: () -> ()) {
        for i in 0..<self {
            task()
        }
    }
}

I know that the task is parameter namer. But I do not know what () -> ().

Upvotes: 7

Views: 3438

Answers (4)

Lu Hao
Lu Hao

Reputation: 1

I had the same confusion when encountering this line of code.

seeing:

extension Int {
    func repetition(task: () -> Void) {
        for _ in 1...self {
            task()
        }
    }
}

I initially thought that this function could be called by:

3.repetition(task: printAtree(of: 5))

It is only after reading the above answers that I realise () -> () refers to closures and must take closures as an argument. Hence to call the function, we use:

3.repetition {
    printAtree(of: 5)
}

Upvotes: 0

Antonio
Antonio

Reputation: 72810

More precisely, () -> () means a closure taking a tuple with 0 values as argument and returning a tuple with zero values. Which is equivalent to saying: a closure taking no arguments and with no return value (or returning void)

Upvotes: 4

akashivskyy
akashivskyy

Reputation: 45220

() -> () just means Void -> Void - a closure that accepts no parameters and has no return value.

Upvotes: 8

FUJI Goro
FUJI Goro

Reputation: 889

() -> () is the type that takes no parameters and return nothing. () -> Void is the same meaning.

Upvotes: 4

Related Questions