You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Objective-C中调用Swift枚举的方法获取字符串?

Swift枚举的description方法在Objective-C中无法直接调用的解决办法

我在Swift SDK中定义了如下枚举,用于输出调试用的description信息:

@objc public enum ResultCode : UInt16 {
    case noError = 0x0000

    @objc public func description() -> String {
        switch self {
        case .noError:
            return "No Error"
        }
    }
}

但在Objective-C中尝试调用该description()方法时报错:

[taskManager.sendRequest requestWithCompletion:^(ResultCode resultCode) {
    NSString *resultCodeDescription = [resultCode description];//Bad receiver type 'ResultCode' (aka 'enum ResultCode')
    NSLog(@"Result code description: %@", resultCodeDescription);
}];

错误提示为Bad receiver type 'ResultCode' (aka 'enum ResultCode'),已知可以在Swift侧给ResultCode添加带@objc的扩展解决,但希望直接在Objective-C文件内实现,请问该怎么做?


解决方法

在Objective-C中,Swift暴露的@objc枚举会被映射为普通的C枚举类型(而非Objective-C对象),所以没法直接调用实例方法。要在Objective-C内解决,有两种可行方案:

方案1:手动实现枚举值到描述的映射

直接在Objective-C里写一个辅助函数,根据枚举值返回对应的描述字符串:

NSString *ResultCodeDescription(ResultCode code) {
    switch (code) {
        case ResultCodeNoError:
            return @"No Error";
        // 后续如果Swift枚举新增case,记得在这里同步补充对应的分支
        default:
            return [NSString stringWithFormat:@"Unknown Result Code: %hu", code];
    }
}

调用的时候直接用这个函数就行:

[taskManager.sendRequest requestWithCompletion:^(ResultCode resultCode) {
    NSString *resultCodeDescription = ResultCodeDescription(resultCode);
    NSLog(@"Result code description: %@", resultCodeDescription);
}];

方案2:通过NSNumber中转调用Swift方法

Swift的@objc枚举虽然在Objective-C里是C枚举,但可以把它包装成NSNumber,再通过performSelector调用Swift侧定义的description()方法:

[taskManager.sendRequest requestWithCompletion:^(ResultCode resultCode) {
    NSNumber *codeNumber = [NSNumber numberWithUnsignedShort:resultCode];
    NSString *resultCodeDescription = [codeNumber performSelector:@selector(description)];
    NSLog(@"Result code description: %@", resultCodeDescription);
}];

这种方式的好处是,如果后续Swift侧的description()方法更新(比如新增枚举case的描述),Objective-C这边不需要修改代码。但要注意performSelector会跳过编译期检查,得确保Swift侧的description()方法确实被@objc修饰且存在。


内容的提问来源于stack exchange,提问作者Avicii4ever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 18:42:17