简体   繁体   English

如何警告 Swift 中函数的调用者

[英]How to warn caller of a func in Swift

I am refactoring a large iOS Swift project gradually.我正在逐步重构一个大型iOS Swift项目。 Some function have to be renamed and I cannot rename directly because many other modules directly calling it.一些 function 必须重命名,我不能直接重命名,因为许多其他模块直接调用它。 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.相反,对于第一阶段的发布,我想让 function 的调用者知道请使用这个函数而不是这个函数。 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, ie length().对于第一阶段,我想同时保留length()count() ,但要警告其他开发人员不要使用现有的,即 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. scope 和模块尺寸的实际实现要广泛得多。

You can manage the availability of a method with @available keyword.您可以使用@available关键字管理方法的可用性。

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:建议用户重命名 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使用available的关键字

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您可以通过多种方式使用它,如果您想向开发人员显示警告,那么您应该使用deprecated ,但是如果您想强制它们,则使用unavailable

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

More information available at HackingWithSwift更多信息可在HackingWithSwift 获得

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM