Swift +macros参数

我读了所有有关macros在Swift问答,而且我确实知道everything in Swift now global,中的everything in Swift now global, 对吗?

而我的实际问题是,如果我有一个macros,我需要parameter passing,那么我怎么能传递它在Swift语言?

例如

Objective-Cmacros

#define COLOR_CODE(red, green, blue, alpha) [UIColor colorWithRed: red/255.0 green: green/255.0 blue: blue/255.0 alpha: alpha]

上面的macros是什么Swift语法?

正如0O0O0O0所提到的那样,“编译器应该看到COLOR_CODE(0, 0, 0, 1) ,并用[UIColor colorWithRed: 0/255.0 green: 0/255.0 blue: 0/255.0 alpha: 1] ”不存在于Swift中。

C中的macros可以用于产生混淆错误信息的方式:

 #define IS_EQUAL_TO_ME(argument) [self isEqual: argument] BOOL func(id argument) { return IS_EQUAL_TO_ME(argument); } // Error: Use of undeclared identifier 'self' 

或者破坏可读性:

 #define OPEN_BLOCK { #define CLOSE_WITH_EXIT_IF_FALSE } else { exit (0); } if (x < 0) OPEN_BLOCK return 10; CLOSE_WITH_EXIT_IF_FALSE 

对于像COLOR_CODE这样简单的例子,一个推荐的C策略就是使用内联函数:

 NS_INLINE UIColor *ColorCode(CGFloat r, CGFloat g, CGFloat b, CGFloat a) { return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]; } 

这与macros具有相同的性能,因为它将被内联到相同的代码,但是是强types的,并且不依赖于macros处理规则。 这段代码也直接翻译成Swift:

 func ColorCode(red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat) -> UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha) } 

因为“一切都是全局的”,你可以在任何文件中声明它,并在同一模块中的任何其他文件中使用它。 在这种情况下由编译器决定是否内联函数。

按照这个文档页面 ,您可能需要将其转换为函数或generics:

“在C和Objective-C中使用复杂的macros,但在Swift中没有对应的复杂的macros,它们是不定义常量的macros,包括括号括起来的函数式的macros,在C和Objective-C中使用复杂的macros来避免type-检查约束或避免重新input大量的样板代码,但是macros可能会使debugging和重构变得困难,在Swift中,可以使用函数和generics来实现相同的结果,而不会有任何折衷。 Objective-C源文件不能用于Swift代码。“

我所做的是创build一个返回#define的类方法。

例:

.h文件:

 #define COLOR_CODE(red, green, blue, alpha) [UIColor colorWithRed: red/255.0 green: green/255.0 blue: blue/255.0 alpha: alpha] + (UIColor*)colorCodeWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha; 

.m文件:

 + (UIColor*)colorCodeWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha { return COLOR_CODE(red, green, blue, alpha); } 

而在Swift中:

由于这是一个类方法,现在可以像使用#define那样使用它了。 如果你改变你的#definemacros,它将反映在你在Swift中创build的新方法中:

let color = YourClass.colorCodeWithRed(72.0,green:55.0,blue:100.0,alpha:1.0);