gpt4 book ai didi

objective-c - 如何在 Objective-C 中使用 Swift String 枚举?

转载 作者:行者123 更新时间:2023-11-29 05:14:41 25 4
gpt4 key购买 nike

我有一个带有 String 值的枚举,它将用于告诉记录到服务器的 API 方法,消息具有什么样的服务器性。我使用的是 Swift 1.2,因此枚举可以映射到 Objective-C

@objc enum LogSeverity : String {
case Debug = "DEBUG"
case Info = "INFO"
case Warn = "WARN"
case Error = "ERROR"
}

我得到了错误

@objc enum raw type String is not an integer type

我还没有找到任何地方说只有整数可以从 Swift 转换为 Objective-C。是这样吗?如果是这样,有人对如何在 Objective-C 中提供类似的功能有任何最佳实践建议吗?

最佳答案

解决方案之一是使用 RawRepresentable 协议(protocol)。

必须编写 init 和 rawValue 方法并不理想,但这允许您在 Swift 和 Objective-C 中像往常一样使用此枚举。

@objc public enum LogSeverity: Int, RawRepresentable {
case debug
case info
case warn
case error

public typealias RawValue = String

public var rawValue: RawValue {
switch self {
case .debug:
return "DEBUG"
case .info:
return "INFO"
case .warn:
return "WARN"
case .error:
return "ERROR"
}
}

public init?(rawValue: RawValue) {
switch rawValue {
case "DEBUG":
self = .debug
case "INFO":
self = .info
case "WARN":
self = .warn
case "ERROR":
self = .error
default:
return nil
}
}
}

关于objective-c - 如何在 Objective-C 中使用 Swift String 枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59304743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com