Swift + 宏参数 [英] Swift + macro parameters

查看:24
本文介绍了Swift + 宏参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了所有与 Swift 中的宏相关的问答,我确实发现 Swift 中的所有内容现在都是全局的, 我说的对吗?

I read all Q&A related to Macros in Swift, And i did figure out that everything in Swift now global, Am i right?

我的实际问题是,如果我有一个需要传递参数的宏,那么我如何以 Swift 语言传递它?

And my actual question is that if i have a macro in which i need parameters to be pass then how can i pass it in Swift language?

例如

Objective-C 宏

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

上述宏的 Swift 语法是什么?

What is the Swift syntax for above macro?

推荐答案

正如 0O0O0O0 提到的,编译器应该看到 COLOR_CODE(0, 0, 0, 1) 意义上的宏并替换它与 [UIColor colorWithRed: 0/255.0 green: 0/255.0 blue: 0/255.0 alpha: 1]" 在 Swift 中不存在.

As 0O0O0O0 mentioned, macros in the sense of "The compiler should see COLOR_CODE(0, 0, 0, 1) and replace it with [UIColor colorWithRed: 0/255.0 green: 0/255.0 blue: 0/255.0 alpha: 1]" do not exist in Swift.

C 中的宏可用于产生令人困惑的错误消息:

Macros in C can be used in ways that produce confusing error messages:

#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 语言策略是使用内联函数:

For simple cases like COLOR_CODE a commonly recommended strategy for C was to use inline functions:

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];
}

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

This had the same performance as the macro in that it would get inlined to the same code but is strongly typed and does not depend on macro processing rules. This code also has a direct translation to 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)
}

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

Because "everything is global" you can declare this in any file and use it in any other file in the same module. It is up to the compiler in this case to decide whether or not to inline the function.

这篇关于Swift + 宏参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆