Created
July 15, 2019 09:03
-
-
Save jimmyhoran/9aa563595cd780405c18701e3407570c to your computer and use it in GitHub Desktop.
Dictionary extension for case insensitive value lookups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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