kaddie
kaddie

Reputation: 283

Swift how to add compiler warning to function

I wrote a simple extension to a viewController and I would like to put a warning so that other developers don't call this function directly. I am not sure if there is an attribute that can serve this purpose in swift :

My code :


internal extension UIViewController {

    // add warning so that it can appear when another developer wants to directly access this function
    func removeFromParent() {

        self.willMove(toParent: nil)
        self.view.removeFromSuperview()
        self.removeFromParent()
    }
}

So when another develop tries to do something like :

let viewController = TestViewController()
viewController.removeFromParent()          

They should get warning that you can't use this function directly

Upvotes: 5

Views: 1417

Answers (2)

emrcftci
emrcftci

Reputation: 3516

Add warning->

Also you can use #error("your message")

internal extension UIViewController {

    #warning("Your warning message")     
    func removeFromParent() {

        self.willMove(toParent: nil)
        self.view.removeFromSuperview()
        self.removeFromParent()
    }
}

Add warning when function called->

internal extension UIViewController {

    //@available(*, unavailable)

    //@available(*, deprecated, message: "your warning message")

    //@available(*, deprecated, renamed: "new name")     

    //@available(swift, introduced: 5)
    func removeFromParent() {

        self.willMove(toParent: nil)
        self.view.removeFromSuperview()
        self.removeFromParent()
    }
}

@available options:

  • unavailable
  • introduced
  • deprecated
  • obsoleted
  • message
  • renamed

If you need more examples please visit hackingwithswift

Upvotes: 4

Thomas
Thomas

Reputation: 1319

add above your function:

@available(*, deprecated, message: "use `someOtherFunction` instead")

You could also add a commentary like this:

/// DEPRECATED: you should use `someOtherFunction` instead

So it appears when your developer use Alt + Click

Upvotes: 6

Related Questions