lundi 26 août 2019

Using reflection to reduce enum boilerplate?

Recently, I found this handy little snippet of code to get the string representation of an enum, even when associated values are present:

enum XXX {
    case a
    case b
    case c(Int)

    private var typeStr: String {
        guard let label = Mirror(reflecting: self).children.first?.label else { 
            return .init(describing: self) 
        }
        return label
    }
}

This is pretty clever. Could reflection also be used to reduce boilerplate like this init function?

init?(rawValue: String?)
{
    guard let val = rawValue?.lowercased() else {
        return nil
    }
    switch val {
        case "a", "1a": self = .a
        case "b", "1b": self = .b
        case "c", "1c": self = .c(1)
        default: return nil
    }
}





Aucun commentaire:

Enregistrer un commentaire