Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert to `AnyObject?`?

In the creation of a swift iOS app, I needed to handle the event of a UIButton press outside of the parent view controller, so I created a (very simple) protocol to delegate that responsibility to a different class:

import UIKit
protocol MyButtonProtocol {
    func buttonPressed(sender: UIButton)
}

However, when I try to addTarget to a UIButton with that protocol, I get this error: Cannot convert value of type 'MyButtonProtocol' to expected argument type 'AnyObject?'. Shouldn't anything be able to be converted to AnyObject?? Here is my main code:

import UIKit
class MyView: UIView {
    var delegate: MyButtonProtocol
    var button: UIButton
    init(delegate: MyButtonProtocol) {
        self.delegate = delegate
        button = UIButton()
        //... formatting ...
        super.init(frame: CGRect())
        button.addTarget(delegate, action: "buttonPressed:", forControlEvents: .TouchUpInside)
        addSubview(button)
        //... more formatting ...
    }
}

Thanks in advance.

like image 741
Mark Anastos Avatar asked Dec 23 '15 05:12

Mark Anastos


1 Answers

AnyObject is the protocol to which all classes conform. To define a protocol which can only adopted by classes, add : class to the definition:

protocol MyButtonProtocol : class {
    func buttonPressed(sender: UIButton)
}

Without that modification,

var delegate: MyButtonProtocol

can be a struct or enum type and that is not convertible to AnyObject.

like image 96
Martin R Avatar answered Oct 11 '22 17:10

Martin R