Type Conversion
In this page:
Numeric Type Conversion
To convert between numeric types like Int and Double, you wrap the value in the target type's initializer -- Swift never converts numbers implicitly.
Example: Numeric Type Conversion
let wholeNumber = 7
let asDouble = Double(wholeNumber)
print("Int: \(wholeNumber), as Double: \(asDouble)")
Login to try C/C++/Java/PHP code in the editor
Converting Strings to Numbers
Converting a String to a number uses a failable initializer that returns an optional, since not every string is a valid number.
Example: Converting Strings to Numbers
let validText = "42"
let invalidText = "hello"
let validNumber = Int(validText)
let invalidNumber = Int(invalidText)
print("Valid: \(String(describing: validNumber))")
print("Invalid: \(String(describing: invalidNumber))")
Login to try C/C++/Java/PHP code in the editor
Converting Numbers to Strings
Turning a number into a String is done either with the String(_:) initializer or through string interpolation, both producing the same text representation.
Example: Converting Numbers to Strings
let count = 100
let asText = String(count)
print("Converted: " + asText)
print("Interpolated: \(count)")
Login to try C/C++/Java/PHP code in the editor
Truncation When Converting Double to Int
Converting a Double to an Int truncates the fractional part rather than rounding, so 4.9 becomes 4, not 5.
Note: Use .rounded() before converting if you want rounding instead of truncation.
Example: Truncation When Converting Double to Int
let price = 4.9
let truncated = Int(price)
print("4.9 truncated to Int: \(truncated)")
Login to try C/C++/Java/PHP code in the editor
- Trying to convert a non-numeric string to
Int, e.g.Int("hello"), without handling the resultingnilfrom the failable initializer. - Assuming numeric conversions like
InttoDoublehappen automatically; Swift always requires an explicit conversion call. - Forgetting that converting a
DoubletoInttruncates the decimal part rather than rounding it.
- Converting between numeric types requires an explicit initializer call, like
Double(someInt). - Converting a
Stringto a number uses a failable initializer, e.g.Int("42"), which returns an optional. - Converting a number to a
Stringis done withString(someNumber)or interpolation. Int(someDouble)truncates toward zero rather than rounding.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: