@@ -357,24 +357,31 @@ extension RandomAccessCollection<String> {
357
357
///
358
358
/// - Parameters:
359
359
/// - key: The key or name of the argument, e.g. `"--attachments-path"`.
360
+ /// - index: Optionally, the index where `key` should be found.
360
361
///
361
362
/// - Returns: The value of the argument named by `key`. If no value is
362
363
/// available, returns `nil`.
363
364
///
364
365
/// This function handles arguments of the form `--key value` and
365
366
/// `--key=value`. Other argument syntaxes are not supported.
366
- fileprivate func argumentValue( forKey key: String ) -> String ? {
367
- if let index = firstIndex ( of: key) {
367
+ fileprivate func argumentValue( forKey key: String , at index: Index ? = nil ) -> String ? {
368
+ guard let index else {
369
+ return indices. lazy
370
+ . compactMap { argumentValue ( forKey: key, at: $0) }
371
+ . first
372
+ }
373
+
374
+ let element = self [ index]
375
+ if element == key {
368
376
let nextIndex = self . index ( after: index)
369
377
if nextIndex < endIndex {
370
378
return self [ nextIndex]
371
379
}
372
380
} else {
373
381
// Find an element equal to something like "--foo=bar" and split it.
374
382
let prefix = " \( key) = "
375
- let index = self . firstIndex { $0. hasPrefix ( prefix) }
376
- if let index, case let key = self [ index] , let equalsIndex = key. firstIndex ( of: " = " ) {
377
- return String ( key [ equalsIndex... ] . dropFirst ( ) )
383
+ if element. hasPrefix ( prefix) , let equalsIndex = element. firstIndex ( of: " = " ) {
384
+ return String ( element [ equalsIndex... ] . dropFirst ( ) )
378
385
}
379
386
}
380
387
@@ -498,9 +505,7 @@ func parseCommandLineArguments(from args: [String]) throws -> __CommandLineArgum
498
505
499
506
// Filtering
500
507
func filterValues( forArgumentsWithLabel label: String ) -> [ String ] {
501
- args. indices. lazy
502
- . filter { args [ $0] == label && $0 < args. endIndex }
503
- . map { args [ args. index ( after: $0) ] }
508
+ args. indices. compactMap { args. argumentValue ( forKey: label, at: $0) }
504
509
}
505
510
let filter = filterValues ( forArgumentsWithLabel: " --filter " )
506
511
if !filter. isEmpty {
0 commit comments