Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue to inherit UIAlertAction in Swift

Here is my code:

class CustomAlertAction: UIAlertAction {
    init(title : String) {
        super.init(title: title, style: UIAlertActionStyle.Default) { (action) -> Void in
        }
    }
}

But I got the following compiling error:

Must call a designated initializer of the superclass 'UIAlertAction'

I know the designated initializer of UIAlertAction is init(). But the init(title, style, handler) of UIAlert will not call its designated initializer init()?

Any idea? Thanks

P.S.: Based on the Apple's document:

A designated initializer must call a designated initializer from its immediate superclass.”

Does this mean it's not allowed to inherit UIAlertAction in Swift? It's no problem to do so in Objective-C.

The reason why I want to create a subclass of UIAlertAction is because I want to add a ReactiveCocoa command as an action.

like image 821
Bagusflyer Avatar asked Jul 14 '15 23:07

Bagusflyer


2 Answers

The solution is realistically almost certainly to use class extensions instead.

extension UIAlertAction {
    convenience init(title: String) {
        self.init(title: title, style: .Default, handler: nil)
    }
}

Usage:

let okayAction = UIAlertAction(title: "Okay")

You can still subclass the UIAlertAction to add properties to it. The subclass can still use this convience initializer you extended off of UIAlertAction class.


Finally, for what it's worth, someone has already created a Reactive Cocoa UIAlertAction subclass. They just did it in Objective-C. Seeing how there's no harm in adding Objective-C to your project, you could just take this approach... or just install that pod...

like image 143
nhgrif Avatar answered Sep 18 '22 12:09

nhgrif


Like @nhgrif said, using an extension is the way to go. It's a complementary way to write expressiveness code.

Example:

/// App alert actions
extension UIAlertAction {
    static var cancel: UIAlertAction {
        return UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
    }
    class func sharePhoto(handler: ((UIAlertAction) -> Void)?) -> UIAlertAction {
        return UIAlertAction(title: "Share", style: .Default, handler: handler)
    }
}

Use it like

alertController.addAction(.cancel)

alertController.addAction(.sharePhoto({ action in
    print(action)
}))
like image 42
ricardopereira Avatar answered Sep 20 '22 12:09

ricardopereira