Swift与C Bridge枚举内部构件和元数据

ryoqjall  于 2023-01-04  发布在  Swift
关注(0)|答案(1)|浏览(109)
    • 问题:**

为什么基本相同的枚举的输出不一样?Swift是否从C中剥离了元数据(我假设它是由编译器剥离的,然后由Swift接口文件再次提供,就好像它是一个普通的Swift枚举一样)?

    • 详细信息:**

我有两个类似的枚举,一个用C定义,另一个用Swift定义。
然而,我得到了不同的打印结果,特别是Swift Enum能够将键打印为一个代表性的String(在本例中为first),但C Enum只能打印枚举名称(在本例中为CNames)。
这是程序的输出,

Enumerations in Swift and C
Running on Swift 5
CNames is 1
first is 1
Program ended with exit code: 0

我假设Swift主文件正在使用Swift生成的接口。
1.这是我的项目的样子:

1.下面是我的原生Swift枚举'Snames:

//
//  SNames.swift
//  TestAppMain
//

import Foundation

public enum SNames : UInt {
    case unknown = 0
    case first = 1
    case middle = 2
    case last = 3
}

1.下面是我的枚举CNames

#ifndef Names_h
#define Names_h

// NSUInteger type definition
#import <Foundation/NSObjCRuntime.h>

typedef NS_ENUM(NSUInteger, CNames) {
    NameUnknown = 0,
    NameFirst   = 1,
    NameMiddle  = 2,
    NameLast    = 3,
};

#endif /* Names_h */

1.以下是生成的Swift 5界面

// NSUInteger type definition
import Foundation.NSObjCRuntime

public enum CNames : UInt {
    case unknown = 0
    case first = 1
    case middle = 2
    case last = 3
}

1.下面是我的桥接标头:

#ifndef TestAppMain_Bridging_Header_h
#define TestAppMain_Bridging_Header_h

#import "CNames.h"

#endif /* TestAppMain_Bridging_Header_h */

1.最后我的main.swift是:

print("Enumerations in Swift and C")
#if swift(>=5)
    print("Running on Swift 5")
#endif

let cFirst = CNames.first
let sFirst = SNames.first

// Swift Enum is able to output the specific
// case (i.e first) whereas the C Enum
// doesn't seem to have that info
// CNames is 1
print("\(cFirst) is \(cFirst.rawValue)")
// first is 1
print("\(sFirst) is \(sFirst.rawValue)")
8gsdolmq

8gsdolmq1#

这只是C的一个局限性。C枚举只不过是一组可视的整数常量。
您会注意到,在将@objc应用于Swift枚举时,会遇到相同的限制:

enum NativeEnum: Int32 { case i = 123 }
print(NativeEnum.i) // => "i"

@objc enum ExportedEnum: Int32 { case i = 123 }
print(ExportedEnum.i) // => "ExportedEnum"

相关问题