Swift enum property *without* initializing the enum case with an associated value?

Probably not what you want, but:

enum MyEnum {
    case valueNone
    case valueString(String?)
    case valueExpensive(CustomDataTypeThatsExpensiveToConstruct?)
    
    var associatedValueTypeString: String {
        switch self {
        case .valueNone:         return "none"
        case .valueString(_):    return "string"
        case .valueExpensive(_): return "custom"
        }
    }
    
}

struct CustomDataTypeThatsExpensiveToConstruct { }

print(MyEnum.valueNone.associatedValueTypeString)           // "none"
print(MyEnum.valueString(nil).associatedValueTypeString)    // "string"
print(MyEnum.valueExpensive(nil).associatedValueTypeString) // "custom"
1 Like