DevPrep

All topics › Programming basics

Data type

Junior

Essence

A data type defines two things: the set of allowed values and the set of operations on them. Int is the integers from Int.min to Int.max plus arithmetic; Bool is two values plus &&, ||, !. The type tells the compiler how to interpret the bytes in memory and which calls are legal.

Swift's type system

let count = 42            // Int — inferred by the compiler
let ratio = 0.5           // Double
let flag = true           // Bool
let name = "Swift"        // String
let ch: Character = "S"
let maybe: Int? = nil     // Optional<Int>

let total = Double(count) * ratio   // conversions are explicit only

Value vs reference — the key split

struct Money { var cents: Int }                       // value type
final class Account { var money = Money(cents: 0) }   // reference type

var m1 = Money(cents: 100)
var m2 = m1
m2.cents = 5
print(m1.cents, m2.cents)          // 100 5 — the copy is independent

let a1 = Account()
let a2 = a1
a2.money.cents = 7
print(a1.money.cents)              // 7 — both references point to one object

struct, enum, every standard collection and String are value types: assignment copies the value (lazily for collections — copy-on-write). class, actor and closures are reference types: only the reference is copied.

Optional and abstract types

Optional<T> is an enum with cases .none and .some(T): absence is expressed in the type, not through a "magic" nil or 0. Unwrap with if let, guard let, ??, ?.; use ! only when nil is genuinely impossible.

An abstract data type is an interface without an implementation. In Swift that is a protocol: Collection describes the operations, while Array and Set implement them differently.

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store