Home > Software engineering >  How to add warning to all uses of native swift function/method?
How to add warning to all uses of native swift function/method?

Time:05-11

standard way of adding warnings is:

class someClass {
    #warning("Your warning message") 
    //@available(*, unavailable)
    //@available(*, deprecated, message: "your warning message")
    //@available(*, deprecated, renamed: "new name")
    //@available(swift, introduced: 5)
    func someFuncWithWarning() {}
}

but what if I need to add warning to native function of swift?

lets imagine that I need to add warning to someString.hasSuffix("suffix") method "Do not use this method"

Is it possible to do this?

CodePudding user response:

I don't think you can. So, I believe you have only two options

First:

protocol Warnings {

    #warning("Your warning message")
    func hasSuffix(_ suffix: String) -> Bool
}

extension String: Warnings {}

But in this case warning will not be placed where you call a function. Instead, it will be placed where you used #warning.

Second:

If you really don't want anyone to use some function

extension String {

    func hasSuffix(_ suffix: String) -> Bool {
        fatalError("Do not use this method")
    }
}

CodePudding user response:

#warning #error and @available are useful for different reasons:

Both #error and #warning work in the same way

#error ("Your error message")
warning ("Your warning message")

And also work alongside if which will trigger only if the condition is true

#if os(macOS)
#error("this is not supported on macOS.")
#endif

But more importantly, you can use @available for deprecated or renamed functions and moreover.

@available(*, deprecated, message: "This function is deprecated") func parseData() { }

@available options

  • deprecated
  • renamed
  • unavailable
  • introduced
  • Related