Last active
March 8, 2018 11:57
-
-
Save erica/ccf504618840dd48e65c to your computer and use it in GitHub Desktop.
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 | |
// Extend String to support regex searching by conforming | |
// to CustomStringConvertible | |
extension String: CustomStringConvertible { | |
public var description: String {return self} | |
} | |
// Regex support for keys | |
public extension Dictionary where Key: CustomStringConvertible { | |
/// Return keys that match the supplied Key expressed as string | |
public subscript (regexKeys regex: Key) -> [Key] { | |
get { | |
// I went with a pretty flexible case insensitive | |
// search here. Tweak as desired. | |
let options: NSStringCompareOptions = [ | |
.RegularExpressionSearch, | |
.CaseInsensitiveSearch, | |
.DiacriticInsensitiveSearch | |
] | |
let stringRex = String(regex) | |
return keys.filter({ | |
// Thanks Patrick Smith, http://twitter.com/concreteniche/status/701906479645794304 | |
return ($0.description as NSString) | |
.rangeOfString(stringRex, options: options) | |
.location != NSNotFound | |
}) | |
} | |
} | |
/// Return values that match the regex Key | |
public subscript (regex regex: Key) -> [Value] { | |
return self[regexKeys: regex].flatMap({ self[$0] }) | |
} | |
} | |
let sample = [ | |
"monday": "mValue", | |
"tuesday": "tValue", | |
"weds": "wValue", | |
"thursday": "thValue"] | |
print(sample[regex: ".*day"]) | |
print(sample[regexKeys: ".*day"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment