Reputation: 11
I am a student in my first computer science class. I am trying to figure out how to set the variable so that it takes a number that is attached to a command our teacher set up called ./integerProperties . Please look at the code I have written, I could use some assistance in how to take that input, and plug it into my variable called number.
27 │Example output for: ./integerProperties 1983
28 │
29 │ The number is even:
30 │ false
31 │ The number is odd:
32 │ true
33 │ The number is evenly divisible by three:
34 │ true
35 │ The number is evenly divisible by five:
36 │ false
37 │ The number is evenly divisible by seven:
38 │ false
39 │ How many groups of ten?
40 │ 198
41 │ How many groups of hundred?
42 │ 19
43 │ The additive inverse:
44 │ -1983
45 │
46 │
47 │
48 │ */
49 │ let firstParameter = CommandLine.arguments[1]
50 │ var number: Int
51 │
52 │ print("The number is even:")
53 │ print(number % 2 == 0)
54 │ print("The number is odd ")
55 │ print(number % 2 != 0)
56 │ print("the number is evenly divisible by 3")
57 │ print(number % 3 == 0)
58 │ print("the number is evenly divisible by 5")
59 │ print(number % 5 == 0)
60 │ print("the number of evenly divisible by 7")
61 │ print(number % 7 == 0)
62 │ print("how many groups of ten")
63 │ print(number / 10)
64 │ print("how many groups of hundreds")
65 │ print(number / 100)
66 │ print("the additive inverse")
67 │ print(number * -1)
Upvotes: 1
Views: 49
Reputation: 1234
Use Int(String)
to parse the argument to an integer. Note that if the string is not an integer, it will return a nil Int?
, and you should handle this case.
guard let number = Int(firstParameter) else {
fatalError("firstParameter is not an Int")
}
Edit: You should also check that the parameter even exists, otherwise CommandLine.arguments[1]
will fail with index out of bounds.
Upvotes: 1