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

j9per5c4  于 2023-03-16  发布在  Swift
关注(0)|答案(1)|浏览(110)

下面是一个协议“Sortable”,用于描述排序、by和ascending。By是一个未知枚举。
Sortable跟在RawRepresentable后面,需要实现from/to rawValue。协议的rawValue是“(按.rawValue),(升序.intValue)",但是当我需要从rawValue中获取self时,“按(rawValue:Int(list[0])??0)”是一个可选的枚举值,如何为其提供一个默认的枚举值?我不知 prop 体的枚举值,我只知道“By:原始值可表示,其中原始值==整数”

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)"
    }
}

更新
我得到了一个解决方案,添加一个“静态变量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)"
    }
}
xfb7svmp

xfb7svmp1#

根据@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)"
    }
}

相关问题