如何在 swift 中使用 objc/c 的嵌套定义?

How to use nesting defines from objc/c in swift?

我有一些来自库供应商的定义的 C 头文件。定义外观:

#define TEST_DEFINE_1 0x12340000
#define TEST_DEFINE_2 TEST_DEFINE_1
    
#define TEST_USE_DEFINE_1 (TEST_DEFINE_1| 0x0001)
#define TEST_USE_DEFINE_2 (TEST_DEFINE_2| 0x0001)

我想在我的 swift 代码中使用这些定义,所以我添加了桥接头:

#ifndef Bridging_Header_h
#define Bridging_Header_h

#include "defines.h"

#endif /* Bridging_Header_h */

并使用它们:

print(TEST_DEFINE_1)
print(TEST_DEFINE_2)
print(TEST_USE_DEFINE_1)

// This line causes error "Cannot find 'TEST_USE_DEFINE_2' in scope"
print(TEST_USE_DEFINE_2)

所以我不能将嵌套定义与算术一起使用。

swift/xcode有问题吗?还是我做错了?

有最小示例的回购:https://github.com/aatriff/define_test

查看 working with C macros in Swift 的文档。

以下是相关部分:

Swift automatically imports simple, constant-like macros, declared with the #define directive, as global constants. Macros are imported when they use literals for string, floating-point, or integer values, or use operators like +, -, >, and == between literals or previously defined macros.

C macros that are more complex than simple constant definitions have no counterpart in Swift. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises.


编辑
这是我以前使用过的解决方法:

在Bridging_Header.h中添加一个包装函数

    int exposeTestUseDefine2()
    {
        return TEST_USE_DEFINE_2;
    }

main.swift

    print(exposeTestUseDefine2())