Created
July 17, 2019 00:39
-
-
Save damuellen/d473f06a82ec6ac06d12e3f9b6e31674 to your computer and use it in GitHub Desktop.
CommandLineOptions with DynamicMemberLookup
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
extension CommandLine { | |
@dynamicMemberLookup | |
public struct Options { | |
private let dict: [String : String] | |
public init?(_ arguments: [String]) { | |
let keysWithValues = arguments.dropFirst().compactMap(parse) | |
if keysWithValues.isEmpty { return nil } | |
self.dict = Dictionary(keysWithValues) { $1 } | |
} | |
public subscript(dynamicMember member: String) -> String? { | |
return dict[member] | |
} | |
} | |
static var options: Options? { return Options(arguments) } | |
static func parse(argument: String) -> (String, String)? { | |
let splits = argument.split(separator: "=", maxSplits: 2) | |
guard splits.count > 1 else { return nil } | |
let name = String(splits[0].dropFirst()).lowercased() | |
if name.isEmpty { return nil } | |
let value = String(splits[1]) | |
return (name, value) | |
} | |
} | |
if let options = CommandLine.options, | |
let username = options.user | |
{ | |
print(username) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment