Romeo Sierra Romeo Sierra - 11 days ago 4
Swift Question

Swift - "Expected type before ->": When adding a target to a button

I have the following snippet which I am trying therein to add a target to a button I have created. That gives me an error

Expected type before "->"
. What am I doing wrong? I am a newbie here in swift and kinda confused with what's going on. Anyone mind explaining me what's happening here exactly?

//MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)->()), for: .touchDown)
addSubview(button) //This is the line that is indicated as erratic
}


EDIT
This is what I am following up (one of Apple's pages). There the line is different. That way it indicates an error
Type 'RatingControl' has no member 'ratingButtonTapped'
where the member is defined inside the class.

EDIT 2
Following is the method
ratingButtonTapped(_:)->Void


func ratingButtonTapped(button: UIButton){
print("Button pressed

Answer

You cannot use a closure () -> () as a selector. Remove ->()

#selector(RatingControl.ratingButtonTapped(_:))

and make sure that the method

func ratingButtonTapped(sender : UIButton) { ... }

or in Swift 3

func ratingButtonTapped(_ sender : UIButton) { ... }

is implemented.

The target self assumes that the method is implemented in the current class.

Comments