Named facts — the numbers, names and lists of iOS development

recall · folio

In one line: the exact values, case lists and call orders that UIKit, Foundation, SwiftUI and the test frameworks fix by definition, and the names that patterns and principles were given by their authors — each checked against Apple’s documentation, the Swift Book or the originator. The why behind each lives in the linked folios.

Download PDF Print view LaTeX source

Named facts — the numbers, names and lists of iOS development — figure 1

Auto Layout

namevalue / rule
installed prioritychanging it to or from .required after the constraint is added throws
autoresizing masktranslatesAutoresizingMaskIntoConstraints: true for a view made in code, false from Interface Builder; leave it alone on arrangedSubviews, cells, a VC’s view
conflictengine breaks constraints until the layout is valid, logs; breakpoint UIViewAlertForUnsatisfiableConstraints; never required hugging / compression
self-sizing rowsrowHeight and estimatedRowHeight default to .automaticDimension; an IB cell needs rowHeight = .automaticDimension in code; estimate ≠ 0; heightForRowAt overrides and runs for every row (Apple: hurts at 1000+)
size classUIUserInterfaceSizeClass: .compact · .regular · .unspecified, per axis; set by device, window, multitasking

UIStackViewdefaultcases
axis.horizontal.horizontal · .vertical
distribution (along axis).fill.fill · .fillEqually · .fillProportionally · .equalSpacing · .equalCentering
alignment (across).fill.fill · .leading (= .top) · .firstBaseline · .center · .trailing (= .bottom) · .lastBaseline
spacing0a minimum for the two equal… kinds; negative overlaps; spacingUseSystem (iOS 11)

Networking & Codable

Named facts — the numbers, names and lists of iOS development — figure 2

URLSession reports only client-side errors; a 404 arrives as a response (as? HTTPURLResponse).

URLError.Code (NSURLErrorDomain)
-999cancelled-1009notConnectedToInternet
-1000badURL-1011badServerResponse
-1001timedOut-1020dataNotAllowed (cellular refused)
-1003cannotFindHost-1022appTransportSecurityRequiresSecureConnection
-1004cannotConnectToHost-1200secureConnectionFailed
-1005networkConnectionLost-1202serverCertificateUntrusted

DecodingError: .typeMismatch(type, ctx) · .valueNotFound(type, ctx) (null for a non-optional) · .keyNotFound(key, ctx) · .dataCorrupted(ctx); Context = codingPath, debugDescription, underlyingError. EncodingError: only .invalidValue. Keys: CodingKeys enum (per key) or keyDecodingStrategy: .useDefaultKeys (default) · .convertFromSnakeCase — capitalise after each _, drop inner _, keep leading / trailing ones: base_uri → baseUri, never baseURI · .custom. Dates: default .deferredToDate = Date’s own Codable: a Double, seconds since 1 Jan 2001 (978 307 200 s after 1970) — Unix time needs .secondsSince1970; also .millisecondsSince1970 · .iso8601 · .formatted · .custom.

URLSession
startevery task is created suspended → resume()
callback queuedelegate calls + completion handlers on delegateQueue; nil → a serial queue the session creates, not main
asyncdata(from:) (iOS 15) → (Data, URLResponse)
configs.default (disk cache, keychain) · .ephemeral (RAM only) · .background(withIdentifier:) (system process; force-quit cancels)
numbersrequest timeout 60 s, reset by each arriving byte · resource 7 days · 6 connections per host, HTTP/1.1 only
ownershipdelegate held strongly until invalidate… — else a leak; .shared: no delegate, no custom config, no background
challengeurlSession(_:didReceive:completionHandler:) → .useCredential · .performDefaultHandling · .cancelAuthenticationChallenge · .rejectProtectionSpace

Lifecycle enums & kill codes

UIApplication.State and SwiftUI ScenePhase: .active · .inactive · .background. Scenes opt in via UIApplicationSceneManifest (iOS 13); UIKit logs a message without it from iOS 18.4. TN3187: applicationDidBecomeActive → sceneDidBecomeActive, likewise WillResignActive, DidEnterBackground, WillEnterForeground. Hang: most Apple tools report a main run loop busy > 250 ms; < 100 ms is rarely noticed. 0x8badf00d watchdog · 0xdead10cc file / SQLite lock held while suspending · 0xc00010ff thermal · 0xbaadca11 VoIP push without a CallKit report.

SOLID — R. C. Martin’s own one-liners

S A class should have one, and only one, reason to change. · O You should be able to extend a classes behavior, without modifying it. · L Derived classes must be substitutable for their base classes. · I Make fine grained interfaces that are client specific. · D Depend on abstractions, not on concretions.

Touches: down to find, up to handle

Named facts — the numbers, names and lists of iOS development — figure 3

A presented VC’s next responder is the presenting VC; the app delegate joins only if it is a UIResponder. hitTest(_:with:) skips isHidden, isUserInteractionEnabled = false, alpha < 0.01; a point outside a view’s bounds never hits its subviews, even with clipsToBounds = false; transparent pixels still hit. Gesture recognizers get touches before the view; a nil-target action searches the chain.

Memory & value semantics

weakunowned
formalways var, Optionalnon-optional or Optional
target diesARC sets nil (no observers fire)access = runtime error; unowned(unsafe) is unchecked
use whenthe other lives shorterthe other lives as long or longer
var a = 0, b = 0; let c = { [a] in print(a, b) }; a = 10; b = 10; c() prints 0 10: list entries are copied when the closure is created; a class reference copies the reference. weak var delegate: P? needs protocol P: AnyObject. Copy-on-write: arrays, dictionaries, strings share storage until a copy is modified; own structs only by hand — isKnownUniquelyReferenced(_:) counts strong refs only, needs synchronisation. static let: lazy, initialised once even across threads; lazy var: no such guarantee. No mutating call on a let struct. deinit: classes, actors and ~Copyable structs / enums (SE-0390, Swift 5.9). Apple: structs by default; classes for Objective-C interop or controlled identity. Tools: Debug Memory Graph (+ scheme Malloc Stack for backtraces) · Allocations, Mark Generation around one feature · leaks: unreferenced malloc buffers + root cycles · the simulator never warns or kills for memory.

SwiftUI state

wrapperiOSrule
@State13owned; also holds an @Observable model
@Binding13read / write a source of truth elsewhere ($x)
@StateObject14created once per container lifetime
@ObservedObject13an input — never a default value; not for @Observable
@Observable17macro; a view updates only for properties body reads
@Bindable17bindings into an @Observable
Migration: StateObject → State · EnvironmentObject → Environment + .environment(_:) · ObservedObject → plain property · @Published → nothing (@ObservationIgnored opts out). some View: opaque result type, SE-0244, Swift 5.1.

Testing

Pyramid (Cohn, Succeeding with Agile, 2009): Unit · Service · UI; inverted = ice-cream cone. 70/20/10 is Google Testing Blog 2015, “as a good first guess” — not Cohn. Test doubles (Meszaros, xUnit Test Patterns, 2007): Dummy passed around, never used — fills parameter lists · Fake working shortcut implementation (an in-memory database) · Stub canned answers to calls made during the test · Spy a stub that also records how it was called · Mock pre-programmed expectations = the specification of the calls. XCTest: class setUp() → per test: setUp() async throws → setUpWithError() → setUp() → test → teardown blocks (LIFO) → tearDown() → tearDownWithError() → tearDown() async throws → class tearDown(); a crash skips teardown. Swift Testing (Swift 6, Xcode 16): #expect records and continues; #require throws ExpectationFailedError, try #require(opt) unwraps; parallel by default (XCTest: one by one); traits .disabled .enabled(if:) .bug .tags .timeLimit .serialized; exit tests Swift 6.2, not on iOS.

Patterns & principles — the authors’ words

GoF (Gamma, Helm, Johnson, Vlissides, 1994) — 23: 5 creational Abstract Factory, Builder, Factory Method, Prototype, Singleton · 7 structural Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy · 11 behavioural Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor.

Adapterconverts an interface into the one clients expect
Decoratorsame interface, adds responsibilities at run time — vs “an explosion of subclasses to support every combination”
Facadeone higher-level interface over a subsystem
Proxysurrogate that controls access: remote · virtual (create on demand) · protection · smart reference
Strategyinterchangeable algorithms; the client picks, so it must know them
Stateobject “will appear to change its class”; transitions in the Context or (more flexible) in the states
Factory M.subclasses decide which class to instantiate — one product
Abstract F.families of related objects, no concrete classes named (“Kit”)
Template Method = “Hollywood principle: Don’t call us, we’ll call you” · Mediator: many-to-many → one-to-many · Command → queue, log, undo (UndoManager.registerUndo) · Observer: NotificationCenter selector observers need no removal since iOS 9, block observers do; AnyCancellable cancels on deinit · Builder’s Director · Iterator = IteratorProtocol.next() (nil = end) + Sequence.makeIterator() · Coordinator (Khanlou, 2015) · “Dependency Injection”: name settled in Fowler’s Jan 2004 article (constructor / setter / interface injection) — a technique; DIP is a principle.

Report a problem ·Discuss this folio