Ad space (banner)
๐ŸฆSwift Lessons
Lesson 31 / 68

Type Conversion (Casting) Basics

In this lesson you will learn the basics of type conversion in Swift so you can move between strings and numbers. This is for anyone searching for "Swift Int String conversion".

Type conversion (casting) - string to number, number to string - is a fundamental programming operation. You use Int() and String().

The sample code turns the string "123" into an integer with Int(str)! and uses it in arithmetic, then turns the number 45 into a string with String(n). Because an unconvertible string yields nil, this is also a good exercise in handling Optionals safely.

A common stumbling block for beginners is force-unwrapping with !. Unwrapping the Optional that Int() returns properly is the basis of safe Swift, and using ! on a value that might fail to convert is a crash waiting to happen.

In real-world development, safe unwrapping with if let or guard let is strongly preferred in real Swift code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)