Swift Tutorial

Data Types

Integers, Doubles, Booleans, and the powerful Tuple type

The Standard Types

Swift provides a familiar set of basic data types.
TypeDescription
IntWhole numbers (64-bit on most platforms)
Double64-bit floating point numbers (Default for decimals)
Float32-bit floating point numbers
Booltrue or false
StringA collection of characters
CharacterA single Unicode character

Number Formatting

Swift allows you to use underscores in numbers to make them more readable. This is great for large values.
swift
let oneMillion = 1_000_000

Tuples

Wait! Tuples are a unique feature in Swift. They allow you to group multiple values into a single compound value. The values within a tuple can be of any type.
swift
let httpError = (404, "Not Found")

// You can also name the elements
let user = (name: "Alpha", age: 25)
print(user.name)
Tuples are perfect for returning multiple values from a function without having to define a whole new class or struct.

Type Aliases

You can give an existing type a new, more descriptive name using the typealias keyword.
swift
typealias AudioSample = UInt16

Summary

TermDescription
IntThe default integer type
DoubleThe default floating-point type
BoolBooleans (must be true or false)
TupleGrouped values: (1, "A")
TypealiasGiving a type a custom name
OverflowSwift prevents numeric overflows by default (Crash vs Corruption)
Best ForRepresenting different shapes of data safely
LogicStrong types ensure data is used correctly
SafetyNo implicit conversion (You must cast Int to Double manually)
ModernTuples and Type Inference make code very readable
StandardUse Int even if your data fits in a smaller type
IdentityData types in Swift are actually structs!