Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 146 ยท Getting Started

Basic Types

A tour of Swift's basic types - Int and sized integers, Double, Float, Bool, Character and String, literals, type safety and why conversions are explicit.

Every value in a Swift program has a type, and the compiler knows it. The type decides which operations are allowed (you can add two numbers, but not a number and a word), how much memory the value occupies, and how it behaves when you copy it. This lesson introduces the types you will use in nearly every program: integers, floating-point numbers, booleans, characters and strings. The next lessons go deeper on Working with Numbers and Strings.

All of these types are structs in the standard library, which is why they have methods and properties, such as Int.max or "abc".count.

Integers

Int is the integer type you should use by default. On a 64-bit platform (everything our server runs) it holds values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Swift also has fixed-size integers when you need a specific width, for example for file formats or network data: Int8, Int16, Int32, Int64, and unsigned versions UInt8, UInt16, UInt32, UInt64. There is also UInt, but the Swift guidance is use Int even for values that can never be negative, such as an array count. Mixing signed and unsigned types in the same calculation is a frequent source of conversion noise and subtle bugs.

Swift Integer ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each type has min and max properties. The signed 8-bit type stops at 127; the unsigned one reaches 255 because it does not need a sign bit.

Integer literals

You can write integer literals in several bases, and underscores can group digits for readability:

Swift Literal forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Floating-point numbers

Double is a 64-bit floating-point number with about 15-16 significant decimal digits. Float is 32-bit with about 6-7. Swift's default for a literal like 3.14 is Double, and the standard advice is to use Double unless an API demands Float.

Swift Double versus Float

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Double.pi has many more digits than Float.pi. The second half of the example shows a fact about every language that uses binary floating point: 0.1 + 0.2 is 0.30000000000000004, not 0.3, because neither 0.1 nor 0.2 can be stored exactly. Never compare floating-point results with ==; compare against a tolerance. If you need exact decimal arithmetic, such as for money, use Decimal (Working with Numbers) or store integer cents.

Floating-point types also have special values. Division by zero does not trap for Double:

Swift Infinity and NaN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get inf, -inf and a NaN ("not a number"), which this platform prints as -nan because the sign bit of the result is set; other platforms may print nan. Do not rely on how a NaN is printed. A NaN is not equal to anything, not even itself, so test for it with .isNaN. (Writing Double.nan == Double.nan compiles with a warning that it is always false.)

Bool

Bool has exactly two values, true and false. Conditions in if and while must be a Bool; Swift does not treat 0, nil or an empty string as "falsy".

Swift Booleans and conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

&& (and), || (or) and ! (not) combine booleans. toggle() flips a Bool in place. Bool("true") returns an optional, and Bool("yes") is nil, because only the exact text "true" and "false" are recognized.

Swift An Int is not a Bool (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: type 'Int' cannot be used as a boolean; test for '!= 0' instead. Write if items != 0 (or better, if items > 0). This rule removes the classic bug of writing = where you meant ==.

Characters and strings

A String is a sequence of text; a Character is one user-perceived character. Both use double quotes, so the type has to come from the context:

Swift Character versus String

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The flag is one Character built out of two Unicode scalars. Swift's Character models what a reader sees as one symbol (a grapheme cluster), which is why counting characters is correct for emoji and combined accents. Details follow in Strings.

Type safety and no implicit conversion

Swift does not convert between types behind your back. Adding an Int and a Double is a compile error:

Swift Mixing Int and Double (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'. Convert explicitly, choosing the direction you mean:

Swift Explicit conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Double(apples) creates a new Double from the integer. Int(3.9) drops the fractional part and gives 3; Int(-3.9) gives -3 (it truncates toward zero, it does not round). Initializers that can fail, such as Int("12.5"), return an optional, here nil. A conversion that cannot be represented traps: Int(Double.nan) or Int(1e30) stops the program.

This explicitness may feel strict, but it makes each lossy step visible in the code, which is exactly where bugs hide.

Literals are an exception: 2 * 0.5 compiles, because the literal 2 can be a Double. Literals have no fixed type until the compiler sees how they are used. A variable holding 2 is an Int already.

Type aliases and choosing a type

You can name an existing type with typealias, which helps readability:

Swift A type alias

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Meters is just another name for Double; the compiler treats them as identical. (If you need the compiler to prevent mixing meters and feet, make a small struct instead. That is the idea behind strong typing, see Structs.)

A quick guide to choosing:

  • Whole numbers: Int.
  • Fractions, measurements, averages: Double.
  • Yes/no: Bool.
  • Text: String; a single symbol: Character.
  • Fixed-width data, bytes, binary formats: UInt8, Int32, and so on, only where the width matters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type should you normally use for an array index or count, even if it is never negative?

    Swift's guidance is to use Int by default, which avoids signed/unsigned conversion problems. Array.count itself is an Int.
  2. 2. What does 0.1 + 0.2 == 0.3 evaluate to for Double values?

    Binary floating point cannot store 0.1 or 0.2 exactly; the sum is 0.30000000000000004. Compare with a tolerance instead.
  3. 3. Why does if count { ... } fail when count is an Int?

    Swift requires a Bool condition, so write count != 0 or count > 0.
  4. 4. What is Int(-3.9)?

    Converting a Double to Int truncates toward zero; it does not round.
  5. 5. What is the result of Int("12.5")?

    The string initializer accepts only valid integer text, so it returns an optional that is nil here.

Summary

  • Use Int for whole numbers and Double for fractions; sized integers are for fixed-width data.
  • Floating-point arithmetic is approximate: compare with a tolerance, and use Decimal or integer cents for money.
  • Bool is the only valid condition type; Character is one user-perceived symbol, String is text.
  • Swift never converts numeric types implicitly; use Double(x), Int(x) and friends.
  • Failing conversions (Int("abc")) return optionals; impossible ones (Int(Double.nan)) trap.
  • typealias gives a type another name but does not create a new type.

Next: Working with Numbers