Search code examples
iosarraysswiftenumscase-insensitive

Matching string value associative enums in an array in a case insensitive way


How would you alter this code to ensure that both res1 and res2 are true?

enum Type: Equatable {
    case int(Int)
    case string(String)
}

func typesContain(_ type: Type) -> Bool {
    let types: [Type] = [.string("abc"), .string("def")]
    return types.contains(type)
}

let res1 = typesContain(.string("abc")) // true
let res2 = typesContain(.string("ABC")) // false

Apologies if an answer already exists, I did search, but...


Solution

  • You just need to define Equatable conformance yourself. And for the case of comparing two string cases, use string.caseInsensitiveCompare instead of the default synthesised implementation, which just uses == for the two String associated values.

    enum Type {
        case int(Int)
        case string(String)
    }
    
    extension Type: Equatable {
        static func ==(lhs: Type, rhs: Type) -> Bool {
            switch (lhs, rhs) {
            case (.int(let num), .int(let otherNum)):
                return num == otherNum
            case (.string(let string), .string(let otherString)):
                return string.caseInsensitiveCompare(otherString) == .orderedSame
            default:
                return false
            }
        }
    }