Ad

Is The Function Name In The Extension Should Be Really Unique Or Not In Swift

- 1 answer

I'd like to ask about naming the Swift extension function. I have an extension file for a UIViewController and created a function called showAlert in the file. I thought the name showAlert might (or might not) be used as the method of default Swift UIViewController in the future update, and I was wondering if I need to change the name of the function to something really unique or I don't really need to change the name at all. If the UIViewController has a function called showAlert with the same parameters in the future Swift update, (which I guess it's not gonna happen) and I have the same name function in the extension file, is it going to be a compiler error? If so, I may need to change the name of the method to something very exclusive to the project.

in case, my code is like

extension UIViewController {

    func showAlert(title: String?, message: String?, actions: [UIAlertAction], style: UIAlertController.Style, completion: (() -> Void)? = nil) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: style)
        actions.forEach { alert.addAction($0)}
        present(alert, animated: true, completion: completion)
    }
}

something like this.

Ad

Answer

and I have the same name function in the extension file, is it going to be a compiler error?

Yes

I was wondering if I need to change the name of the function to something really unique

Nah, just write it in the way that makes your code best. Don’t make your code ugly just to make it defensive.

I think the only issue you might run into is if two libraries both declare the same extension. If the extension is one that you wrote yourself, you should get an error if it’s redeclaring a method that already exists.

Ad
source: stackoverflow.com
Ad