Created
July 2, 2019 02:54
-
-
Save arpitdsoni/4b058e38f50f79db7a08b581d4bb22a4 to your computer and use it in GitHub Desktop.
Create OptionSet from JSON in Swift
This file contains 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
public protocol OptionSetStringIntializing { | |
init?(_ stringValue: String) | |
} | |
public extension OptionSet { | |
static func decode<T>(from strings: [String]) -> T where T: OptionSet, T: OptionSetStringIntializing { | |
var options: T = [] | |
strings.forEach { (str) in | |
if let option = T(str) { | |
options.formUnion(option) | |
} | |
} | |
return options | |
} | |
} | |
extension String.CompareOptions: OptionSetStringIntializing { | |
private enum StrCompareOptions: String { | |
case caseInsensitive | |
case backwards | |
} | |
public init?(_ stringValue: String) { | |
switch stringValue { | |
case StrCompareOptions.caseInsensitive.rawValue: | |
self = .caseInsensitive | |
case StrCompareOptions.backwards.rawValue: | |
self = .backwards | |
default: | |
return nil | |
} | |
} | |
} | |
//Example | |
let jsonArray = ["caseInsensitive", "backwards"] | |
let options: String.CompareOptions = String.CompareOptions.decode(from: jsonArray) | |
options.contains(.caseInsensitive) // true | |
options.contains(.backwards) // true | |
options.contains(.anchored) // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment