clt60
clt60

Reputation: 63932

Command line arguments in swift - convert to interger

Want achieve in swift (MacOS) the following dead-simple perl script:

use strict;
use warnings;
for my $arg (@ARGV) {               #loop over arguments
    next if $arg !~ /^\d+$/;        #skip if not all digits
    print("arg:", $arg + 2, "\n");  #print the number + 2...
}

so invoking this script as: perl script.pl 10 20 30 prints

arg:12
arg:22
arg:32

My "experiment" in swift script called arg.swift:

import Darwin // otherwise the "exit" won't works...

if CommandLine.argc < 2 {
    print("Error", CommandLine.arguments[0], " No arguments are passed.")
    exit(1)
}
    
for i in 1 ..< CommandLine.argc {   // in the "0" is the program name (as above) so skip it
    print("arg:", CommandLine.arguments[i] + 2) // add 2 and print the result
}

running it as swift arg.swift 10 20 30 , prints the following errors..

arg.swift:9:44: error: cannot subscript a value of type '[String]' with an index of type 'Int32'
        print("arg:", CommandLine.arguments[i] + 2)     // add 2 and print the result
                                           ^
arg.swift:9:44: note: overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>), (Range<Self.Index>), ((UnboundedRange_) -> ())
        print("arg:", CommandLine.arguments[i] + 2)     // add 2 and print the result

Honestly, absolutely don't understand what is wrong, so why CommandLine.arguments[0] works, and it complains about CommandLine.arguments[i]... Also, what(?) about overloads?

if someone needs, using:

$ swift --version
Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)
Target: x86_64-apple-darwin17.7.0

Upvotes: 1

Views: 1378

Answers (1)

Gereon
Gereon

Reputation: 17864

All arguments are passed as Strings, so if you want to use them as Ints, you need to add the conversion.

Also, argc is an UInt32 and needs to be converted as well so that you can use it as a subscript index.

For example, like so:

for i in 1 ..< Int(CommandLine.argc) {
  if let intValue = Int(CommandLine.arguments[i]) {
    print("arg:", intValue + 2)
  }
}

Upvotes: 1

Related Questions