如何在协议扩展中设置可选的枚举默认值?

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

这是一个协议'Sortable'来描述排序,按和升序。 By 是一个未知的枚举。

Sortable 遵循 RawRepresentable,需要实现 from/to rawValue。协议的 rawValue 是“(by.rawValue),(ascending.intValue)”,但是当我需要从 rawValue 获取自我时,“By(rawValue: Int(list[0]) ?? 0)”是一个可选的枚举值,我如何为它提供默认的枚举值?我不知道具体的枚举值。我只知道“By: RawRepresentable where By.RawValue == Int”

protocol Sortable: RawRepresentable where RawValue == String {
    associatedtype By: RawRepresentable where By.RawValue == Int
    
    var by: By { get set }
    var ascending: Bool { get set }
    
    init(by: By, ascending: Bool)
}

extension Sortable {
    init?(rawValue: RawValue) {
        let list = rawValue.split(separator: ",").compactMap { $0.isEmpty ? nil : "\($0)" }
        guard list.count == 2 else { return nil }
        let by = By(rawValue: Int(list[0]) ?? 0) ??                      <===== HERE
        let ascending = Int(list[1])?.boolValue ?? true

        self.init(by: by, ascending: ascending)
    }

    var rawValue: RawValue {
        return "\(by.rawValue),\(ascending.intValue)"
    }
}

更新

我有一个解决方案,添加一个“static var defaultBy: By { get }”,但它不是很好。有什么想法吗?

protocol Sortable: RawRepresentable where RawValue == String {
    associatedtype By: RawRepresentable where By.RawValue == Int
    
    var by: By { get set }
    var ascending: Bool { get set }
    static var defaultBy: By { get }
    
    init(by: By, ascending: Bool)
}

extension Sortable {
    init?(rawValue: RawValue) {
        let list = rawValue.split(separator: ",").compactMap { $0.isEmpty ? nil : "\($0)" }
        guard list.count == 2 else { return nil }
        let by = By(rawValue: Int(list[0]) ?? 0) ?? Self.defaultBy
        let ascending = Int(list[1])?.boolValue ?? true

        self.init(by: by, ascending: ascending)
    }

    var rawValue: RawValue {
        return "\(by.rawValue),\(ascending.intValue)"
    }
}
swift enums protocols
1个回答
0
投票

根据@Joakim Danielson 的建议,这很简单也很好!!谢谢!!!

protocol Sortable: RawRepresentable where RawValue == String {
    associatedtype By: RawRepresentable where By.RawValue == Int
    
    var by: By { get set }
    var ascending: Bool { get set }
    
    init(by: By, ascending: Bool)
}

extension Sortable {
    init?(rawValue: RawValue) {
        let list = rawValue.split(separator: ",").compactMap { $0.isEmpty ? nil : "\($0)" }
        guard list.count == 2,
              let byInt = Int(list[0]), let by = By(rawValue: byInt),
              let ascendingInt = Int(list[1]) else { return nil }
        let ascending = ascendingInt.boolValue
        self.init(by: by, ascending: ascending)
    }

    var rawValue: RawValue {
        return "\(by.rawValue),\(ascending.intValue)"
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.