Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4: Cannot assign value of type '(_) -> Void' to type '(() -> ())?'

Tags:

closures

swift

XCode 9, Beta 3. Swift 4.

    let button = JumpingButton(x: 0, y: 50, w: 150, h: 300) // JumpingButton: UIButton
    //Inside JumpingButton: // var clickAction: (() -> ())?


    button.clickAction = { (sender) -> Void in //Error line
        action()
        Sound.playSound(Sounds.Button)
    }

Getting the error: Cannot assign value of type '(_) -> Void' to type '(() -> ())?'

like image 318
Esqarrouth Avatar asked Jul 17 '17 18:07

Esqarrouth


3 Answers

Because clickAction expects a parameter-less function/closure. Simply change your code to:

button.clickAction = {
    action()
    Sound.playSound(Sounds.Button)
}
like image 147
Code Different Avatar answered Oct 19 '22 20:10

Code Different


I don't know anything about the API of these functions (you never told us what they are), but here's what the error tells you:

Cannot assign value of type

It's referring to parameter passing, which is a kind of "assignment"

'(_) -> Void'

This is the type of the argument you gave to the parameter. It has some parameter of an unknown type (_), and returns (->) Void.

to type '(() -> ())?'

This is the type of argument that was expected for this parameter. It has no parameters (()), it returns (->) Void (()), and it's Optional ((...)?)

So the issue is that you're passing a closure with a parameter as an argument to a parameter that expects a parameter-less closure.

like image 3
Alexander Avatar answered Oct 19 '22 19:10

Alexander


I had a similar problem, I resolved this way:

button.clickAction = { _ in
        action()
        Sound.playSound(Sounds.Button)
    }

Hope it helps you.

like image 1
Pablo Blanco Avatar answered Oct 19 '22 18:10

Pablo Blanco