Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive Dictionary in Swift

Tags:

swift

swift2

Given a Dictionary whose Key is of type String, is there a way to access the value in a case-insensitive manner? For example:

let dict = [
    "name": "John",
    "location": "Chicago"
]

Is there a way to call dict["NAME"], dict["nAmE"], etc. and stil get "John"?

like image 493
Code Different Avatar asked Oct 17 '15 02:10

Code Different


1 Answers

A cleaner approach, swift 4:

extension Dictionary where Key == String {

    subscript(caseInsensitive key: Key) -> Value? {
        get {
            if let k = keys.first(where: { $0.caseInsensitiveCompare(key) == .orderedSame }) {
                return self[k]
            }
            return nil
        }
        set {
            if let k = keys.first(where: { $0.caseInsensitiveCompare(key) == .orderedSame }) {
                self[k] = newValue
            } else {
                self[key] = newValue
            }
        }
    }

}

// Usage:
var dict = ["name": "John"]
dict[caseInsensitive: "NAME"] = "David" // overwrites "name" value
print(dict[caseInsensitive: "name"]!) // outputs "David"
like image 128
maxkonovalov Avatar answered Oct 11 '22 10:10

maxkonovalov