快速替换Objective-C宏 [英] Swift replacement for Objective-C macro
问题描述
我忙于用Swift重写应用程序,并希望将以下宏转换为Swift代码.
I busy rewriting an app in Swift and would like to convert the following macro to Swift code.
#define FLOG(format, ...) NSLog(@"%@.%@ %@", [self class], NSStringFromSelector(_cmd), [NSString stringWithFormat:format, ##__VA_ARGS__])
如何将其定义为Swift函数,以便可以在任何地方用于调试日志记录目的,或者是否可以通过另一种方法来实现同一目的?
How can I define this as a Swift function such that I can use if anywhere for debug logging purposes, or is there an alternate way to achieve the same thing?
推荐答案
最简单的方法可能是利用字符串插值并使用:
The easiest way is probably to take advantage of string interpolation and use:
func FLOG(message:String, method:String = __FUNCTION__) {
println("\(method): \(message)")
}
然后您的用法类似于:
FLOG("Illegal value: \(value)")
将方法参数默认为__FUNCTION__
意味着通常将其替换为调用函数名称.您可以使用的其他自动变量包括__FILE__
,__LINE__
和__COLUMN__
.不幸的是__PRETTY_FUNCTION__
不再可用.
Having the method argument default to __FUNCTION__
means that it will normally be replaced with the calling function name. Other automatic variables that you could use include __FILE__
, __LINE__
and __COLUMN__
. Unfortunately __PRETTY_FUNCTION__
is no longer available.
如果您要对消息格式进行更多控制,而不是字符串插值允许,请查看
If you want more control over the formatting of the message than string interpolation allows, take a look at this question which demonstrates simplifying access to printf-style formatting in Swift, and would let you do:
FLOG("Illegal value: %x" % [value])
另请参阅来自Apple的此帖子,该地址使用__FILE__
和assert
See also this post from Apple that addresses using __FILE__
and __LINE__
in assert
这篇关于快速替换Objective-C宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!