Learn/Swift/3. Reading input and arithmetic
Lesson 3 of 8
Sign in

Swift, lesson 3

Reading input and arithmetic

Most useful programs take some input, do a calculation and print the result. In this lesson you read text the user types (or that a test feeds in), turn it into numbers and work with them.

Reading a line

readLine() reads one line from standard input and gives it back as a String, without the new-line character at the end. There is a catch: when there is nothing left to read, there is no line to return. So readLine() does not return a plain String, it returns a String?, an optional string. An optional either holds a value or holds nil, meaning "nothing here".

Swift will not let you use an optional as if it were a normal value. You must decide what happens when it is nil. The friendliest tool is the , which means "use the value if there is one, otherwise use this default":

2 exercises to try what you just read.

Exercise 1

Pizza party

Press Ctrl Enter or Check to test your code.

Exercise 2

Celsius to Fahrenheit

Press Ctrl Enter or Check to test your code.

nil-coalescing operator
??

Turning text into numbers

Input always arrives as text. "42" is two characters, not the number forty-two. To convert, call Int(...) or Double(...) with the string. Those conversions can fail too (what number is "pizza"?), so they also return optionals. Chain ?? again to pick a fallback:

You may see code like Int(readLine()!)!. The ! force-unwraps an optional: it says "I'm sure there is a value". If you are wrong, the program crashes. Prefer ?? while you learn.

Arithmetic operators

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23
%remainder7 % 21

Look closely at 7 / 2. When both sides are Int, Swift does integer division and throws the fraction away. Use Double values when you want 3.5. The remainder operator % gives what is left after dividing, and its result takes the sign of the left-hand number, so -7 % 2 is -1.

Swift never mixes Int and Double silently. let half = guests / 2.0 is a compile error when guests is an Int; write Double(guests) / 2.0 instead.

Usual maths rules apply: *, / and % happen before + and -, and parentheses go first.

Updating a variable

Compound assignment operators update a variable in place: +=, -=, *=, /= and %=.

Swift has no ++ or --; write += 1 instead.

One more safety feature: if an Int calculation goes past Int.max (about 9.2 quintillion), Swift stops the program with an overflow error instead of quietly producing a wrong number.

Further reading

  • Basic Operators
  • The Basics: optionals and numeric conversion
  • readLine(strippingNewline:) in the standard library

Slices of pizza are shared equally among friends, and any slices that can't be shared fairly are left over.

Input: two lines. The first is the number of slices (0 or more), the second is the number of people (at least 1).

Output: two lines, Each: followed by the slices per person, and Left: followed by the leftover slices.

Sample input:

Sample output:

Read a temperature in degrees Celsius and print it in degrees Fahrenheit, using F = C × 9 / 5 + 32. The input can have a decimal part, so work with Double.

Input: one line with a number, such as 37 or -12.5.

Output: the Fahrenheit value on one line. Print the Double directly; small rounding differences are accepted.

Sample input:

Sample output:

let name = readLine() ?? "stranger"
print("Hi, \(name)!")
let line = readLine() ?? ""
let guests = Int(line) ?? 0
let price = Double(readLine() ?? "") ?? 0.0
var score = 10
score += 5   // 15
score *= 2   // 30
14
4
Each: 3
Left: 2
100
212.0