Swift Type Inference & Conversion
Swift is strongly typed, yet you rarely have to write types. The compiler infers them from context. When you do want a value of a different type, you must convert it explicitly — Swift never does it behind your back.
Type inference
The compiler looks at the initial value (or the surrounding expression) to decide the type:
let count = 12 // Int
let price = 4.99 // Double
let title = "Notebook" // String
let inStock = true // Bool
let total = Double(count) * price
print(type(of: count), type(of: price), type(of: title), type(of: inStock))
print(type(of: total), total)Int Double String Bool
Double 59.88
An integer literal combined with a decimal literal is inferred as Double — let mixed = 3 + 0.5 gives 3.5. This works because literals have no fixed type yet. Two already-typed variables are different:
let apples = 3
let weightPerApple = 0.25
let totalWeight = apples * weightPerApple
print(totalWeight)error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:3:26: error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
1 | let apples = 3
2 | let weightPerApple = 0.25
3 | let totalWeight = apples * weightPerApple
| |- error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
| `- note: overloads for '*' exist with these partially matching parameter lists: (Double, Double), (Duration, Double), (Int, Int)
4 | print(totalWeight)
Converting numbers
Create a new value of the target type by calling the type like a function:
import Foundation // needed here for rounded() on Linux
let apples = 3
let weightPerApple = 0.25
let totalWeight = Double(apples) * weightPerApple
print(totalWeight)
let temperature = 21.8
print(Int(temperature)) // truncates toward zero
print(Int(temperature.rounded())) // rounds to the nearest whole number
print(Int(-7.9))0.75
21
22
-7
| Conversion | Result | Note |
|---|---|---|
Double(5) |
5.0 |
always succeeds |
Int(9.99) |
9 |
drops the fractional part |
Int(9.99.rounded()) |
10 |
rounds first |
Int8(300) |
crash | the value must fit in the target type |
Int8(exactly: 300) |
nil |
safe version that returns an optional |
Converting to and from strings
Turning any value into text is easy with String(...) or interpolation. Going the other way can fail — "hello" is not a number — so Int("...") and Double("...") return an optional: either a value or nil.
let n = 42
let text = String(n)
print(text + "!")
let input1 = "128"
let input2 = "12.5"
let input3 = "twelve"
print(Int(input1) ?? 0)
print(Int(input2) ?? -1) // "12.5" is not an integer
print(Double(input2) ?? 0)
print(Int(input3) ?? -1)42!
128
-1
12.5
-1
?? is the nil-coalescing operator: it uses the value on the left if there is one, otherwise the default on the right. You will meet optionals properly in the Optionals chapter.
Booleans and characters
let flag = true
print(String(flag))
print(Bool("true") ?? false, Bool("yes") ?? false)
let letter: Character = "A"
print(String(letter) + "BC")
print(letter.asciiValue ?? 0)
print(Character(UnicodeScalar(66)))true
true false
ABC
65
B
Tip: When the inferred type isn't the one you want, add an annotation instead of converting:
let ratio: Double = 3stores3.0directly.
Test yourself
What is the type of let x = 10 / 4?
- Double
- Int
- Float
- It does not compile
What does Int("3.7") return?
- 3
- 4
- nil
- A compile error
Given let a = 2 and let b = 1.5, how do you multiply them?
- a * b
- Double(a) * b
- a.toDouble() * b
- (Double) a * b