如何在SwiftUI中使TextAlignment可编码?

问题描述 投票:0回答:1

我知道如何使用rawValue使自定义枚举遵守Codable协议,但是有没有办法使内置本机枚举正常工作?

我希望能够存储和检索TextAlignment值,而不必重新发明轮子并创建一些自定义解决方案。

我在任何地方都找不到一个示例!

ios swift enums swiftui codable
1个回答
0
投票

不幸的是暂时没有。

[您可以将它们转换为类似\(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))
    }

}

此方法非常安全。一个缺点是我们可能会收到-101以外的值。我们将这种情况视为center。您可以考虑抛出一个错误。

© www.soinside.com 2019 - 2024. All rights reserved.