Enum of tuples in Swift

6 Solutions Collect From Internet About “Enum of tuples in Swift”

It depends what you mean by “similar”. What I do is use a Struct with static constant properties:

struct Trouble {
    static let Generic_Error = (0, "Unknown")
    static let DB_Error = (909, "Database")

Now things like Trouble.Generic_Error are usable throughout your code.

Swift enumerations cannot have Tuples as a raw value type.

Alternative approaches include storing the code and deriving a description from that:

enum ErrorCode: Int, CustomStringConvertible {
    case Generic = 0
    case DB = 909

    var description: String {
        switch self {
        case .Generic:
            return "Unknown"
        case .DB:
            return "Database"

…or storing associated values for code and description in the enumeration cases themselves:

enum Error {
    case Generic(Int, String)
    case DB(Int, String)

If you’re just looking for constant values, @matt’s suggestion of organizing them within a struct would work, too.

you can do such thing, maybe:

enum ErrorCode {
    case Generic_Error
    case DB_Error

    func values() -> (code: Int!, description: String?)! {
        switch self {
        case .Generic_Error:
            return (0, "Unknown")
        case .DB_Error:
            return (909, "Database")

and you can do such thing later:

let errorCode: ErrorCode = ErrorCode.Generic_Error;
if (errorCode.values().code == 0) {
    // do the business here...

Solution similar to @holex, but instead of a function you can use a var.

enum SomeType {
    case type1
    case type2
    case type3

    var typeNameAndDescription: (name: String, description: String) {
       switch self {
       case .type1:
            return ("type1 name", "type1 description")
        case .type2:
            return ("type2 name", "type2 description")
        case .type3:
            return ("type3 name", "type3 description")

and later:

let myType = SomeType.type1
let typeName = myType.typeNameAndDescription.name
let typeDescription = myType.typeNameAndDescription.description

You can conform to RawRepresentable and use (Int, String) as the Self.RawValue associated type.

enum ErrorCode: RawRepresentable {
    case Generic_Error
    case DB_Error

    var rawValue: (Int, String) {
        switch self {
        case .Generic_Error: return (0, "Unknown")
        case .DB_Error: return (909, "Database")

    init?(rawValue: (Int, String)) {
        switch rawValue {
        case (0, "Unknown"): self = .Generic_Error
        case (909, "Database"): self = .DB_Error
        default: return nil