C and derivatives have argc
and argv
(and envp
) parameters to their entry point functions, but Swift doesn't have one proper: top-level code is just code and it doesn't have parameters.
How can one access the equivalent of argc
and argv
in a Swift program?
Process.arguments
is your friend!Fortunately this is much easier, and built in: no importing anything, no getting your hands dirty with C, objective or otherwise.
Consider this, let's call it
args.swift
:Swift 2 version:
Swift 3 version:
We can compile and run it like this:
Note that the first argument is the program name, as you might expect.
It seems every argument is a String, as you might also expect.
I hope very much that
Process
becomes more useful as Swift matures, but right now it seems to only give you the arguments. Which is a lot, if you're trying to write a pure-Swift program.Process was just renamed into CommandLine (since Swift 3.0 August 4 snapshot)
(for some reason this wasn't mentioned on the changelog)
For Swift 3 you can use this code:
which is equivalent of
argc
andargv
parameters used in Objective-C main function:For older versions of Swift, you can use
Process.argc
andProcess.unsafeArgv
orC_ARGC
andC_ARGV
.You can pass this variables to
UIApplicationMain
function in iOS app:Swift 3:
previous Swift versions:
or:
Objective-C:
As in the above code, you can use C_ARGC to get number of arguments. C_ARGV to get this arguments.
As soon as your app is up I'd use the process info:
Nothing unsafe there, very convenient.
Note that you have to
import Foundation
(orCocoa
/UIKit
).