Skip to content

Instantly share code, notes, and snippets.

@jimmyhoran
Created July 15, 2019 09:03
Show Gist options
  • Save jimmyhoran/9aa563595cd780405c18701e3407570c to your computer and use it in GitHub Desktop.
Save jimmyhoran/9aa563595cd780405c18701e3407570c to your computer and use it in GitHub Desktop.
Dictionary extension for case insensitive value lookups
import Foundation
extension Dictionary where Key == String {
func valueForInsensitive<T>(key: Key) -> T? {
let key = keys.first { $0.compare(key, options: .caseInsensitive) == .orderedSame } ?? key
return self[key] as? T
}
}
// MARK: Example
var parameters: [String: Any] = [
"ID": 12345678,
"userName": "50Cent",
"lengthOfLife": 50
]
let id: Int? = parameters.valueForInsensitive(key: "id")
let username: String? = parameters.valueForInsensitive(key: "username")
let age: Int? = parameters.valueForInsensitive(key: "lengthOfLife")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment