← Back to Swift Course | Chapter 2: Variables & Types | Lesson 8 of 8

Type Conversion

Type conversion means turning one kind of value, like a number, into a different kind, like text, so different parts of your program can work together.

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

markup
let wholeNumber = 7
let asDouble = Double(wholeNumber)
print("Int: \(wholeNumber), as Double: \(asDouble)")

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

markup
let validText = "42"
let invalidText = "hello"
let validNumber = Int(validText)
let invalidNumber = Int(invalidText)
print("Valid: \(String(describing: validNumber))")
print("Invalid: \(String(describing: invalidNumber))")

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

markup
let count = 100
let asText = String(count)
print("Converted: " + asText)
print("Interpolated: \(count)")

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

markup
let price = 4.9
let truncated = Int(price)
print("4.9 truncated to Int: \(truncated)")
Common Mistakes
  1. Trying to convert a non-numeric string to Int, e.g. Int("hello"), without handling the resulting nil from the failable initializer.
  2. Assuming numeric conversions like Int to Double happen automatically; Swift always requires an explicit conversion call.
  3. Forgetting that converting a Double to Int truncates the decimal part rather than rounding it.
Chapter Summary
  • Converting between numeric types requires an explicit initializer call, like Double(someInt).
  • Converting a String to a number uses a failable initializer, e.g. Int("42"), which returns an optional.
  • Converting a number to a String is done with String(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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.