Beginbydeclaringatypethatdefinestheinformationthatyouneedtocollectfromthecommandline.DecorateeachstoredpropertywithoneofArgumentParser'spropertywrappers,andthendeclareconformancetoParsableCommandandaddthe@mainattribute.Finally,implementyourcommand'slogicintherun()method.
importArgumentParser@mainstructRepeat:ParsableCommand{@Flag(help:"Includeacounterwitheachrepetition.")varincludeCounter=false@Option(name:.shortAndLong,help:"Thenumberoftimestorepeat'phrase'.")varcount:Int?@Argument(help:"Thephrasetorepeat.")varphrase:Stringmutatingfuncrun()throws{letrepeatCount=count??.maxforiin1...repeatCount{ifincludeCounter{print("\(i):\(phrase)")}else{print(phrase)}}}}TheArgumentParserlibraryparsesthecommand-linearguments,instantiatesyourcommandtype,andtheneitherexecutesyourrun()methodorexitswithausefulmessage.
ArgumentParserusesyourproperties'namesandtypeinformation,alongwiththedetailsyouprovideusingpropertywrappers,tosupplyusefulerrormessagesanddetailedhelp:
$repeathello--count3hellohellohello$repeat--count3Error:Missingexpectedargument'phrase'.Help:<phrase>Thephrasetorepeat.Usage:repeat[--count<count>][--include-counter]<phrase>See'repeat--help'formoreinformation.$repeat--helpUSAGE:repeat[--count<count>][--include-counter]<phrase>ARGUMENTS:<phrase>Thephrasetorepeat.OPTIONS:--include-counterIncludeacounterwitheachrepetition.-c,--count<count>Thenumberoftimestorepeat'phrase'.-h,--helpShowhelpforthiscommand.Formoreinformationanddocumentationaboutallsupportedoptions,seethelibrary'sdocumentationinXcode.
ExamplesThisrepositoryincludesafewexamplesofusingthelibrary:
repeatistheexampleshownabove.rollisasimpleutilityimplementedasastraight-linescript.mathisanannotatedexampleofusingnestedcommandsandsubcommands.YoucanalsoseeexamplesofArgumentParseradoptionamongSwiftprojecttools:
indexstore-dbisasimpleutilitywithtwocommands.swift-formatusessomeadvancedfeatures,likecustomoptionvaluesandhiddenflags.ProjectStatusTheSwiftArgumentParserpackageissourcestable;versionnumbersfollowsemanticversioning.SourcebreakingchangestopublicAPIcanonlylandinanewmajorversion.
ThepublicAPIofversion1.0oftheswift-argument-parserpackageconsistsofnon-underscoreddeclarationsthataremarkedpublicintheArgumentParsermodule.Interfacesthataren'tpartofthepublicAPImaycontinuetochangeinanyrelease,includingtheexactwordingandformattingoftheautogeneratedhelpanderrormessages,aswellasthepackage’sexamples,tests,utilities,anddocumentation.
Futureminorversionsofthepackagemayintroducechangestotheserulesasneeded.
We'dlikethispackagetoquicklyembraceSwiftlanguageandtoolchainimprovementsthatarerelevanttoitsmandate.Accordingly,fromtimetotime,weexpectthatnewversionsofthispackagewillrequireclientstoupgradetoamorerecentSwifttoolchainrelease.RequiringanewSwiftreleasewillonlyrequireaminorversionbump.
AddingArgumentParserasaDependencyTousetheArgumentParserlibraryinaSwiftPMproject,addittothedependenciesforyourpackageandyourcommand-lineexecutabletarget:
letpackage=Package(//name,platforms,products,etc.dependencies:[//otherdependencies.package(url:"https://github.com/apple/swift-argument-parser",from:"1.0.0"),],targets:[.executableTarget(name:"<command-line-tool>",dependencies:[//otherdependencies.product(name:"ArgumentParser",package:"swift-argument-parser"),]),//othertargets])
评论