不幸的是现在还不行。
您可以将它们转换为字符串,\(alignment)然后通过迭代allCases并选择一个来恢复,但我不推荐这种方法,因为不能保证名称将来不会更改。
我建议 - 是Codable使用switch...case以下方式实现自定义一致性:
extension TextAlignment: Codable {
/// Adding constants to make it less error prone when refactoring
private static var leadingIntRepresentation = -1
private static var centerIntRepresentation = 0
private static var trailingIntRepresentation = 1
/// Adding a way to represent TextAlignment as Int value
/// You may choose a different type if more appropriate
/// for your coding practice
private var intRepresentation: Int {
switch self {
case .leading: return TextAlignment.leadingIntRepresentation
case .center: return TextAlignment.centerIntRepresentation
case .trailing: return TextAlignment.trailingIntRepresentation
}
}
/// Initializing TextAlignment using Int
/// Making the method private as our intention is to only use it for coding
private init(_ intRepresentation: Int) {
switch intRepresentation {
case TextAlignment.leadingIntRepresentation: self = .leading
case TextAlignment.trailingIntRepresentation: self = .trailing
default: self = .center
}
}
/// Conforming to Encodable
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(intRepresentation)
}
/// Conforming to Decodable
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.init(try container.decode(Int.self))
}
}
Run Code Online (Sandbox Code Playgroud)
这个方法是相当安全的。-1一个缺点是我们可能会收到、0和以外的值1。我们会将这种情况视为center。您可能会考虑抛出一个错误。