Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to warn caller of a func in Swift

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.

like image 899
Sazzad Hissain Khan Avatar asked Oct 31 '19 08:10

Sazzad Hissain Khan


2 Answers

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 { }
like image 66
Mojtaba Hosseini Avatar answered Oct 10 '22 10:10

Mojtaba Hosseini


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

like image 30
Swinny89 Avatar answered Oct 10 '22 09:10

Swinny89