Search code examples
swiftrefactoringextension-methods

Swift - Is there a way run a method on an object without calling the object? (Self?)


Quick question on a few different functions I'm having, all have the same idea. I have an object, and I want to run a function with it. But because it's an extension of the Objects type, I'm calling the object.method(on: object). Is there a way to simplify this so that it runs on itself without having to state it?

Example:

import UIKit

extension UINavigationController {
    
    func removeBackButtonString(on navigationController: UINavigationController) {
        let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        navigationController.navigationBar.topItem?.backBarButtonItem = backButton
    }
    
}

Used in Code:

navigationController?.removeBackButtonString(on: navigationController!)

But is there a way to call it like so?

navigationController?.removeBackButtonString()

Or, to extended a NSManagedObject:

extension Object {
    func setFavorite(object: Object) {
        object.isFavorite = true
    }
}

Use: object.setFavorite(object: object) But how can you tap into the object properties if you don't have the parameter? Example: object.setFavorite()


Solution

  • Yes, you can modify your extension function to something like this:

    extension UINavigationController {        
        func removeBackButtonString() {
            let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
            // `self` is inferred in Swift
            navigationBar.topItem?.backBarButtonItem = backButton
        }
    }
    

    Then, this will run perfectly fine:

    navigationController?.removeBackButtonString()
    

    Update: The same applies also to your second example:

    extension Object {
        func setFavorite() {
            isFavorite = true
        }
    }