Swift 6 cheatsheet
Swift 6: Types and protocols
6 common Swift 6 tasks.
Structs
Structs are value types with memberwise initializers. Mark mutating methods with mutating.
struct Point {
var x: Double
var y: Double
mutating func move(by dx: Double) { x += dx }
}
var p = Point(x: 1, y: 2)
p.move(by: 3)
Classes
Classes are reference types and support inheritance.
class Vehicle {
var wheels = 4
func describe() -> String { "\(wheels) wheels" }
}
class Bike: Vehicle {
override init() { super.init(); wheels = 2 }
}
Enums with associated values
Each case can carry its own data, and switch extracts it.
enum Result {
case success(Int)
case failure(String)
}
switch result {
case .success(let value): print(value)
case .failure(let message): print(message)
}
Protocols and extensions
A protocol describes requirements, and an extension adds default behavior.
protocol Describable {
var name: String { get }
}
extension Describable {
func describe() -> String { "I am \(name)" }
}
struct Dog: Describable { let name: String }
Generics
Write a function once for any type that meets a constraint.
func largest<T: Comparable>(_ items: [T]) -> T? {
items.max()
}
Encode and decode JSON
Conform to Codable and use JSONEncoder and JSONDecoder.
struct User: Codable {
let id: Int
let name: String
}
let data = try JSONEncoder().encode(User(id: 1, name: "Ada"))
let user = try JSONDecoder().decode(User.self, from: data)