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.
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 { }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With