How to warn caller of a func in Swift
Asked Answered
D

2

5

I am refactoring a large iOS Swift project gradually. Some function have to be renamed and I cannot rename directly because many other modules directly calling it. Instead, for the first phase release, I want to let the caller of a function know that please use this func instead of this func. Let me explain with an example,

func length() - > Int {
    //..... some logic
}

Expecting to refactor it in next version to,

func count() - > Int {
    //..... same logic
}

For the 1st phase I want to keep both length() and count() but let other developers be warned not to use existing one, i.e. length(). So I tried with,

func length() - > Int {
    #warning("Please use count() instead")
    //..... some logic
}

But the warning is thrown in the line but not to the caller. So, what are the best way to let caller be informed about wrong call?

Note: The example here is just a simplest form to understand the problem. Actual implementation is much broader in scope and module size.

Deponent answered 31/10, 2019 at 8:55 Comment(0)
C
6

You can manage the availability of a method with @available keyword.

To warn the user:

@available(*, deprecated, message: "Please use count() instead")
func length() - > Int { }

To force the user:

@available(*, unavailable, message: "Please use count() instead")
func length() - > Int { }

To suggest the user to rename the function:

@available(*, renamed: "count()")
func length() - > Int { }

Also you can set the platform and the deprecation version if you need to (even without a message):

@available(iOS, deprecated:11.2)
func length() - > Int { }
Cavern answered 31/10, 2019 at 9:0 Comment(1)
It may be to worth to mention the @available(*, renamed: "count()") option as well, because that offers an inline rename feature in Xcode.Dominion
D
4

Use the available keyword

You can use it in a couple of ways, if you want to show a warning to the developer then you should use deprecated, however if you want to force them then use unavailable

@available(*, deprecated, message: "Please use count() instead")
func length() - > Int {
}

More information available at HackingWithSwift

Damson answered 31/10, 2019 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.