swift - 使用 NSLog 记录 Swift 枚举

标签 swift nslog

我正在尝试记录一个枚举:

enum CKAccountStatus : Int {
    case CouldNotDetermine
    case Available
    case Restricted
    case NoAccount
}

NSLog("%i", CKAccountStatus.Available)

编译器提示:

Type 'CKAccountStatus' does not conform to protocol 'CVarArg'

为什么?我试图投值:

NSLog("%i", CKAccountStatus.Available as Int)

但这也不会飞:

Cannot convert the expression's type '()' to type 'String'

最佳答案

获取枚举的基础 Int 值:CKAccountStatus.Available.rawValue

枚举在 Swift 中不是严格意义上的整数,但如果它们是用底层类型声明的,您可以使用 rawValue 获取它——无论底层类型是什么。 (enum Foo: String 将为您提供 rawValue 等的字符串)如果枚举没有基础类型,则 rawValue 有没有什么可以给你的。在从 ObjC 导入的 API 中,使用 NS_ENUM 定义的任何枚举都有一个基础整数类型(通常是 Int)。

如果您想更详细地打印任何枚举,您可以考虑对采用 Printable 协议(protocol)的枚举类型进行扩展。

关于swift - 使用 NSLog 记录 Swift 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24061735/

相关文章:

ios - 添加项目作为子模块提示错误 Module YapDatabse not found

ios - 如何在 Swift 中获取从 UIPickerViewController 中选取的视频的缩略图?

ios - swift .framework 更新导致 'use of undeclared type errors'

iphone - 我的 NSLog 输出在哪里?

ios - 有什么方法可以用 NSLog 进行彩色打印吗?

ios - 本地图上的标记超过 840 个时,iOS 版 Google map 出现性能问题

ios - UITableView是否滚动到顶部?

iphone - 如何将现有应用程序日志复制到 TestFlight 并使用宏

ios - NSLog内存地址

cocoa - NSLog 10b 含义?