You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@Option(defaultAsFlag:"json", help:"Set the export format.")
337
+
var export: String?
341
338
342
339
funcrun() {
343
-
print("Format: \(format ??"none")")
344
-
print("Port: \(port ??3000)")
340
+
print("Export: \(format ??"<don't export>")")
345
341
}
346
342
}
347
343
```
348
344
349
345
**Command-line behavior:**
350
346
```
351
-
% example # format = nil, port = nil
352
-
% example --format # format = "default", port = nil
353
-
% example --format json # format = "json", port = nil
354
-
% example --port # format = nil, port = 8080
355
-
% example --port 9000 # format = nil, port = 9000
347
+
% example # export = nil
348
+
% example --export # export = "json"
349
+
% example --format yaml # format = "yaml"
356
350
```
357
351
358
352
The `defaultAsFlag` parameter creates a hybrid that supports both patterns:
359
-
-**Flag behavior**: `--format` (sets format to "default")
360
-
-**Option behavior**: `--format json` (sets format to "json")
361
-
-**No usage**: format remains `nil`
353
+
-**Flag behavior**: `--export` (sets format to "json")
354
+
-**Option behavior**: `--export yaml` (sets format to "yaml")
355
+
-**No usage**: `export` remains `nil`
362
356
363
357
#### Type requirements
364
358
@@ -405,7 +399,7 @@ The parser determines whether a value follows the option:
405
399
2.**No value available**: Use the `defaultAsFlag` value
406
400
3.**Explicit value provided**: Parse and use that value
407
401
408
-
This works with all parsing strategies (`.next`, `.scanningForValue`, `.unconditional`), though `.unconditional` defeats the purpose by always requiring a value.
402
+
This works with parsing strategies `.next` and `.scanningForValue`. The `.unconditional` parsing strategy defeats the purpose by always requiring a value.
409
403
410
404
For complete examples and API reference, see the [`default-as-flag`](https://github.com/apple/swift-argument-parser/tree/main/Examples/default-as-flag) example.
0 commit comments