The folios
310 folios
ai
- AI coding agents at work — loop, context, permissions, proof
A coding agent is a model calling tools in a loop inside a harness that decides what each call may touch. You control the context it sees, the permissions and sandbox around it and the check it must pass: rules files advise; permission rules, hooks and sandboxes enforce; a test, build or screenshot proves.
- Core ML · Core AI · Vision — machine learning on the device
A trained model ships as a file; its first load specialises it for this chip and OS and caches the result; it runs on CPU, GPU and Neural Engine. Core ML (iOS 11) runs any model type, Core AI (iOS 27) modern neural nets; Vision, Speech, Natural Language and Foundation Models put Apple’s own models behind task APIs.
- LLM features in a mobile app — backend, stream, guard, pay
An LLM feature is a distributed system with an untrusted component: the app never holds a vendor key — it calls your backend, which authenticates user and app, enforces quotas, assembles the prompt, guards input and output, meters tokens and relays a stream. Everything the model reads can carry instructions; everything it writes is untrusted input to the next system. Safety comes from what the model can do, not from what the prompt says.
architecture
- Client SDK design — a library inside someone else’s app
An SDK is a guest with a contract: a small public surface that is hard to misuse, documented threading (callbacks on a known queue), no crash, no block, no launch cost, errors as values, and a compatibility promise — SemVer at the source level, library evolution at the binary level — enforced by an API-diff check in CI. Every public symbol is forever; shipping it is the easy part, removing it takes a major version.
- Cloud vs on-device — where should it run?
Place each computation where its binding constraint is cheapest: trust (anything authoritative runs on a server — the client is attacker-controlled), knowledge and size (world knowledge, big models, live data → cloud), privacy, offline and latency (personal data, per-frame work, no network → device). Most real features are hybrid: device first, server (or Private Cloud Compute) as the fallback, results cached and versioned.
- Coordinator · Repository · DI · Clean / VIPER
Four ways to stop one object knowing too much. Coordinator — where to go next (navigation out of VCs). Repository — where data comes from (hide network/cache/DB behind one protocol). DI — who builds my collaborators (someone outside, at the composition root). Clean — which way dependencies point (always inward, towards business rules).
- Designing login for a mobile app — the whole system
Login is a system, not a screen. An identity step proves who (password + MFA, passkey, SSO); the server issues a short-lived access token and a server-side, revocable refresh credential bound to this device, which the app keeps in the Keychain and re-opens with biometrics. Refresh, step-up, recovery, logout and rate limits need the same care as the happy path — attackers pick the weakest one.
- GoF: behavioural patterns
Behavioural patterns decide who talks to whom and who decides: Strategy (client picks the algorithm) · State (object switches itself) · Observer (one-to-many notify) · Command (request as object, execute+undo) · Template Method (base skeleton, subclass hooks) · Chain of Responsibility (pass until handled) · Mediator (hub instead of mesh) · Iterator (next() until nil).
- GoF: creational + structural
Creational patterns decide how an object comes to exist (Singleton, Factory Method, Abstract Factory, Builder). The four “wrappers” are told apart by intent, not shape: Adapter changes the interface, Decorator keeps it and adds behaviour, Facade simplifies a whole subsystem, Proxy keeps it and controls access.
- Image loading pipeline — memory, disk, network, decode
A request walks memory (decoded, sized bitmaps) → disk (encoded bytes) → network (deduplicated, prioritised, cancellable) and comes back through decode + downsample off the main thread. What matters: the cache key, the memory maths, one download per key with cancellation only when the last subscriber leaves, an identity check before assigning, and prefetch at low priority.
- iOS client system design — a feed, end to end
Order of decisions: requirements (functional, non-functional, scale) → API + data model → client layers → data flow (read + write) → the hard parts (sync, pagination, images) → trade-offs. On the client the local store is the source of truth; the network syncs into it.
- Large React Native app architecture
A big RN codebase stays fast to change when it is a monorepo of packages with one dependency direction — apps → features → data / UI → native modules — each package exposing a public API ("exports"), boundaries enforced by lint, an owner per package, a task graph that builds and tests only what changed, and exactly one copy of react-native.
- MVC · MVP · MVVM · MVVM-C
All four keep the same Model; they differ in where presentation logic lives and who holds a reference to whom. Each step moves logic out of the UIKit-bound view into a plain, unit-testable object: MVC (controller does it all) → MVP (presenter pushes to a view protocol) → MVVM (view binds to state; VM never sees the view) → MVVM-C (a Coordinator also takes navigation out).
- Push on iOS + Android from one app — FCM, APNs, React Native
Your server addresses installs, not users. Each install gets a token (on iOS the FCM SDK maps the APNs token to an FCM token) and uploads it keyed by user + device; the backend fans out to every live token via FCM HTTP v1 (or APNs directly) and deletes the ones reported dead. What runs on arrival depends on message type, app state and platform.
- Server-driven UI — schema, registry, versions, fallbacks
The server sends a typed description of a screen — layout + components with their data + actions — and the app renders it with native components it already ships. You gain release independence (change a screen without a store release, run experiments, one backend for iOS/Android/web); you pay with a schema to design, every old app version to keep working, and a weaker compile-time contract. It moves data and composition, never code.
- SOLID — five principles, exact words
Single responsibility · Open/closed · Liskov substitution · Interface segregation · Dependency inversion — Robert C. Martin’s rules for code whose parts can change independently. Each below: the exact definition, one iOS example, and which pattern serves it.
- Sync engines — clocks, conflicts, CRDTs
A sync engine keeps replicas (phones, tablets, the server) that accept writes offline and must end in the same state. Record operations, not snapshots, in a durable log; apply them idempotently; detect concurrency with versions or vector clocks (never wall clocks); resolve it with a named policy — server-authoritative, LWW, field merge, OT (a server orders and transforms) or CRDTs (merge is mathematically order-free); keep deletes as tombstones.
- System design — analytics SDK & E2E-encrypted messenger
Same steps, two very different centres of gravity: scope → functional → non-functional → data model → API → high-level → the hard parts. An SDK lives inside someone else’s app: it must never crash, block, bloat or leak it — the design is a persisted, batched, privacy-gated queue. An E2EE messenger’s server is an untrusted mailbox: keys live only on devices, every message is sealed per recipient device, and the push extension has to decrypt.
ble
- BLE in the Apple ecosystem — iBeacon, ASK, ranging, Find My
Apple’s proximity features are different frameworks on one radio: an iBeacon is a BLE advert only Core Location sees; AccessorySetupKit (iOS 18) pairs one accessory without the Bluetooth prompt and now gates Channel Sounding (27) and some background relaunches (26); Nearby Interaction measures over UWB; Find My relays locations encrypted to rotating keys. A plain BLE GATT accessory needs no MFi.
- Bluetooth Mesh · Thread · Matter
Bluetooth Mesh floods tiny double-encrypted messages over BLE advertising — no IP, no connections; Thread is a routed IPv6 mesh on 802.15.4 that reaches the LAN through border routers; Matter is the application layer — data model, PASE / CASE, attestation, fabrics — over Thread, Wi-Fi or Ethernet, set up over BLE (or Wi-Fi USD, NFC).
c
- Bits, masks and hardware registers in C
A register is a fixed address reached through a volatile uint32_t *; a field is a position + width — read it shift, then mask, write it clear, then OR, in unsigned arithmetic with shift counts below the width. r |= m is a load, an OR and a store: SET/CLR registers, bit-band aliases and write-1-to-clear flags exist so that one bit changes in one store.
- C memory layout — sections, alignment, padding, byte order, promotion
Four storage durations, which the toolchain maps to sections: code and constants in .text/.rodata (flash on an MCU), initialised statics in .data (an image copied to RAM at start-up), zero statics in .bss (zeroed, no image bytes), locals on the stack, malloc on the heap. The ABI fixes sizes and alignments; members sit in order at multiples of their alignment, so structs get padding. Byte order is the CPU’s; arithmetic below int happens in int.
- Pointers — declarations, const, restrict, decay, lifetime
A pointer is an address plus a type (the step of p+1, the type of *p) plus one object it may reach — only inside that object, only while it lives. Read a declaration from the name outward: right first ([], ()), then left (*, qualifiers). const binds to what is on its left (if nothing, its right). restrict promises that data modified through the pointer has no other path.
- Undefined behaviour & the C build — preprocess, compile, link
Undefined behaviour is behaviour “for which this document imposes no requirements” (C23 3.5.3). The optimiser assumes it never happens, so checks vanish and loops change shape — often only at -O2, far from the bug. Building = per translation unit preprocess → compile → assemble to a .o; then the linker resolves every symbol to one definition, places the sections and patches the addresses.
- volatile · _Atomic · interrupts — sharing state safely in C
volatile binds only the compiler: every access in the source is performed, none merged or dropped. It gives no atomicity, no ordering of other memory and no CPU barrier. State shared with an interrupt, a signal handler or another CPU needs a lock-free _Atomic, a critical section, or a lock.
cicd
- CI pipeline design — fast feedback, safe merges, one artifact
A pipeline is a DAG of gates ordered so the cheapest check most likely to fail runs first; its critical path is the developer’s wait. Speed comes from content-keyed caches only CI writes and duration-balanced shards; main stays green because a merge queue tests the merge before it lands; the release artifact is built once, attested, and promoted; the whole system is judged by the DORA metrics — not by how many jobs it has.
- fastlane — config, lanes, match internals, store auth
fastlane is a Ruby gem (pin it with Bundler) whose lanes call actions; gym, scan, pilot, deliver, snapshot, match, supply wrap xcodebuild, Apple’s upload tools, the App Store Connect API and the Google Play Developer API. On CI its job is to make signing and upload non-interactive: match decrypts one shared cert/profile store into a throw-away keychain, and an API key (.p8) replaces an Apple ID that needs 2FA.
- GitHub Actions — triggers, trust, runners, tokens
An event starts every workflow in .github/workflows/ whose on: matches; its jobs form a DAG (needs:), each on a fresh runner, running steps in one workspace. Security is which code runs with which token, secrets and cache: the trigger decides, permissions: and cache-mode: narrow it, OIDC replaces stored cloud keys, a commit SHA pins what runs.
- xcodebuild, simctl & friends — Xcode from the command line
xcodebuild runs one action of a scheme against a destination and leaves files you can open — an .xcarchive, an .ipa, an .xcresult. simctl drives simulators, devicectl phones; xcode-select / DEVELOPER_DIR pick which Xcode answers.
cross-platform
- Android background work — which API, and what the OS allows
Android runs your code in the background only on its terms: a coroutine dies with its owner, WorkManager guarantees deferrable work (persisted, survives reboot, runs when quota and constraints allow), a foreground service is visible work the user started, and AlarmManager is for a wall-clock moment. Every release since 6.0 (Doze) has narrowed the rest: standby-bucket quotas, background-start bans, typed and time-limited services.
- Android build & performance — Gradle, R8, profiles, startup
A release build is Gradle (configure a task graph, then run only out-of-date tasks) driving kotlinc/KSP → R8 → dex → AAB; Play splits it per device. At runtime ART interprets/JITs unbundled code such as Compose, so a Baseline Profile tells it what to compile ahead of time at install. Prove every win with Macrobenchmark + Perfetto.
- Android lifecycle, ViewModel & Jetpack Compose
An Activity is destroyed and recreated on every configuration change (rotation, locale, dark mode, window size); the ViewModel survives that, the saved-state Bundle survives process death, and Compose redraws UI as a function of state — re-running only the composables that read a changed State.
- Compose layout & modifiers — constraints, measure, place
Layout is one pass: a parent hands each child Constraints (min/max width, height), the child is measured once and reports a size, the parent places it. A Modifier chain wraps outer → inner; each link may change the constraints going down and the size coming up — order is behaviour.
- Compose recomposition & stability — in depth
Compose re-runs a composable only if it read snapshot State that was written; the phase of the read decides how much work follows (composition → layout → draw), and a re-run parent skips a child whose parameters are stable and equal (strong skipping: unstable ones compared by ===). Performance work = read later, read lower, keep inputs stable.
- Hilt & Dagger in depth — graph, components, scopes, tests
Dagger turns @Inject/@Provides/@Binds into a dependency graph checked at compile time and emits plain factory code — no reflection. Hilt fixes the component tree to Android lifetimes: a binding lives in one component, is visible to that component’s children, and a scope annotation means “one instance per component instance”.
- KMP in practice — library stack, shared architecture, concurrency
A shared module is repositories + use cases + a state holder exposing StateFlow in commonMain, built on Ktor, kotlinx.serialization, SQLDelight, Koin and kotlinx-datetime, with per-platform engines and drivers; each platform binds native UI to it. On iOS, Dispatchers.Main is the main queue and the new memory model (tracing GC, no freezing) lets objects cross threads like on the JVM.
- Kotlin coroutines — internals
The compiler rewrites every suspend fun in continuation-passing style: it gains a hidden Continuation parameter, returns Any?, and its body becomes a state machine whose label says where to resume. A suspension returns COROUTINE_SUSPENDED all the way up and frees the thread; later something calls resumeWith, the dispatcher picks a thread, the machine jumps to the next label. Job, scopes, cancellation = library (kotlinx.coroutines) on top.
- Kotlin coroutines & Flow · Android vs iOS platform
A coroutine is a suspendable computation launched in a scope whose Job tree gives structured concurrency (a parent waits for and cancels its children); cancellation is cooperative. Flow is a cold stream, StateFlow/SharedFlow are hot — the Kotlin twins of async/await, Task, AsyncSequence and Combine subjects.
- Kotlin DSLs, inline functions & delegation
Kotlin’s “syntax” is mostly conventions the compiler rewrites: a lambda typed T.() -> R runs with this: T (builders, Gradle, Compose); inline pastes a function and its lambdas into the caller (no allocation, return leaves the caller, reified works); operator/infix map symbols to named functions; by forwards a property or a whole interface to another object. None of it is dynamic — all resolved at compile time.
- Kotlin Flow — contract, operators, backpressure, hot flows
A Flow is a cold, sequential stream: collect runs the producer in the collector’s coroutine, each value passes every operator before the next is produced, and the producer suspends while the collector works (natural backpressure). Two rules make operators composable: context preservation (only flowOn changes where upstream runs) and exception transparency (never emit from inside a catch). Concurrency and hotness are opt-in: buffer, flowOn, channels, stateIn/shareIn.
- Kotlin Multiplatform — fundamentals & the Swift boundary
KMP compiles one Kotlin codebase to each platform’s native artifact — JVM bytecode for Android, a Kotlin/Native (LLVM) binary shipped as an Objective-C framework for iOS — so you share logic (models, networking, persistence, state) and keep native UI unless you opt into Compose Multiplatform. Swift sees Kotlin through an ObjC header: that header is where every interop trap lives.
- Kotlin the language — for a Swift engineer
Kotlin is Swift’s closest cousin: nullability in the type system, immutable-by-default bindings, sealed hierarchies + exhaustive when, extensions and trailing lambdas. The differences that matter: classes only (no value-type structs — data class is a reference type), JVM generics are erased (reified is the escape), extensions are statically dispatched, and internal means Gradle module.
- Kotlin type system & generics — variance, reified, nullability
Every Kotlin type has a nullable twin; the hierarchy is a lattice with Any? on top and Nothing (no values) at the bottom, so throw, TODO() and return fit any expected type. Generics are invariant unless declared out/in at the class (declaration site) or projected at a use; on the JVM type arguments are erased, so runtime checks see only List<*> — unless an inline function makes T reified.
- Kotlin under the hood — what reaches the JVM
The JVM knows nothing about Kotlin: no top-level functions, no properties, no companions, no default arguments, no value classes, no suspend. kotlinc lowers each feature to plain classes, static methods, synthetic bridges and runtime helper calls (kotlin.jvm.internal.Intrinsics). Knowing the lowering explains Java-interop annotations, boxing costs, $default frames in stack traces, and why a read-only List can still change.
- Navigation Compose — back stack, routes, scoping, Nav 3
A NavController owns a back stack of NavBackStackEntry — each entry is its own Lifecycle, ViewModelStore and SavedState owner — and NavHost shows the top one. Routes are @Serializable classes (2.8+); every navigate() is a push plus NavOptions that pop, dedupe, save and restore. Navigation 3 drops the controller: you own the back stack as a state list.
- Room in depth — codegen, invalidation, migrations, KMP
Room is a compile-time layer over SQLite: KSP reads @Entity/@Dao/@Database, checks every SQL string against the schema and generates the implementation. Observable queries work by SQLite triggers that mark a table dirty; after each transaction the InvalidationTracker re-runs every query that reads that table. The schema version is a contract: every change needs a migration or data is lost.
- The modern Jetpack app stack
Google’s recommended app: UI (Compose) observes StateFlow from a ViewModel, which calls a repository whose single source of truth is the local DB (Room) — the network only writes into it. Hilt builds the graph at compile time; WorkManager runs deferrable work that must survive process death and reboot. Every piece has an iOS twin (green).
crypto
- Block cipher modes — ECB, CBC, CTR, GCM, padding oracles
AES is a keyed permutation of one 16-byte block; a mode makes it a message cipher. ECB shows equal blocks, CBC chains (unpredictable IV + padding), CTR is a stream cipher (unique counters), GCM = CTR + a GF(2128) MAC = AEAD. No confidentiality-only mode protects integrity; a repeated or predictable IV breaks them.
- Encoding vs encryption vs hashing vs signing
Encoding changes the format — anyone reverses it, no secret. Encryption hides content — reversible with a key. Hashing fingerprints — one-way, no key. A MAC (shared key) or a signature (private key) proves who produced the bytes and that they are unchanged. A KDF turns a secret into keys — slowly, when the secret is a password. Choose by the property needed: format, confidentiality, integrity, authenticity, non-repudiation.
- Post-quantum cryptography — ML-KEM, ML-DSA, hybrid TLS
A large quantum computer running Shor’s algorithm breaks every public-key primitive in use — RSA, (EC)DH, X25519, ECDSA, EdDSA — at any key size; symmetric ciphers and hashes stand. Traffic recorded today decrypts then (harvest now, decrypt later), so key exchange moved first: hybrid X25519MLKEM768, default in Chrome, Firefox, iOS 26, OpenSSL and OpenSSH. Since the 2026 estimates, signatures are urgent too: Google and Cloudflare now target 2029 for their whole migration.
- Public-key maths — RSA, Diffie–Hellman, elliptic curves
A trapdoor: cheap one way, infeasible back without a secret. RSA: factoring n = pq. DH: the discrete log of ga mod p. ECC: k from kG; only generic √(n) attacks are known, so a 256-bit curve matches 3072-bit RSA. Shor’s algorithm breaks all three.
- Secure randomness — entropy, DRBGs, platform APIs, nonces, UUIDs, failures
A few hundred bits of real entropy seed a DRBG that expands them into an unlimited, unpredictable stream. Take every key, nonce, IV and token from the OS generator (getrandom, SecRandomCopyBytes, SecureRandom, crypto.getRandomValues); the dangerous moment is before it is seeded, or after its state was copied.
cs
- Cross-language FFI — everything meets at the C ABI
Languages call each other through the C ABI: an unmangled symbol, the platform’s C calling convention, C types (scalars, pointers, plain structs). One side exports C-looking functions (extern "C", Go //export, Swift @c); the other links them (-l, cgo, module map) or dlopens them and declares the types (ctypes, Ruby FFI). Every allocation keeps one owner.
- Cryptography with CryptoKit — AEAD, ECDH, signatures, HPKE, ML-KEM
Symmetric AEAD (AES-GCM, ChaCha20-Poly1305) encrypts and authenticates bulk data under one key and a nonce never repeated under that key; asymmetric keys agree on that key (ECDH → HKDF, or a KEM inside HPKE) and sign (ECDSA, Ed25519, ML-DSA). CryptoKit ships vetted primitives with safe defaults — the job is choosing them, managing keys and nonces, and never inventing a primitive, mode or protocol.
- Data structures — layout, invariant, cost
Every structure is a memory layout plus an invariant that makes some operations cheap and others expensive. Pick by the operation that must be fast, then check the constants: a trip to main memory costs ∼50× an L1 hit, so contiguous memory + cache lines beat pointer chasing at equal big-O.
- Designing data structures — compose for O(1)
Name the operation that must be O(1), pick the structure whose invariant makes it cheap, and when no single structure does all of them, compose two that index the same nodes (hash map for find, list for order; heap for extreme, array for random). Then name the price: memory, amortised vs worst case, thread safety.
- Distributed system design — the toolkit
Servers stateless behind a load balancer; reads taken off the database by caches and replicas; writes split by sharding; slow work on queues; truth settled by a majority. Each step trades scale for a named cost — staleness, lag, hot keys, duplicates.
- Hashing — tables, crypto, rings, passwords, Bloom
A hash maps any input to a fixed-size value. Table hashes want speed, spread and a secret seed against flooding (SipHash); cryptographic hashes want preimage and collision resistance (SHA-256, SHA-3); password hashes want to be slow and memory-hard (Argon2id); a MAC needs a key (HMAC). Collisions always exist — the question is only what it costs to find one.
debugging
- Crash reporting in practice — from signal to fixed
A crash reporter is a pipeline: an in-process handler writes the report at the moment of death, the SDK uploads it on the next launch, the server symbolicates it with the artefacts you uploaded for that exact build, fingerprints it into an issue, alerts on new, regressed or fast-growing issues, and a human triages by users affected. Every stage has a way to silently lose the crash.
- Debugging Swift Concurrency — pool, actors, executors
Tasks run on the cooperative thread pool (as many threads as CPU cores, never grows) or on the main actor’s main thread. The runtime’s contract is forward progress: await suspends and frees the thread; a blocked thread is simply lost. Four failures follow — main-actor blocking (hang), actor contention and pool exhaustion (parallel code turned serial, or deadlock), continuation misuse (leak or crash). Concurrency instruments show task / actor / executor state; System Trace shows why a thread is not running.
- Debugging through a proxy — Charles · Proxyman · mitmproxy · Burp
An HTTPS debugging proxy is a consensual man-in-the-middle: it terminates TLS with a leaf certificate minted on the fly and signed by its own root CA — which you installed and trusted on the device — and opens a second TLS connection to the real server. Whatever refuses that root (pinning, Android’s default distrust of user CAs, clients that ignore the proxy) shows up as a failed handshake or no traffic.
- Logging, signposts & power — from code to field data
Logger writes words into the OS’s unified log (binary, levelled, redacted by default), OSSignposter writes time (intervals and events Instruments draws as tracks), and the OS meters power per subsystem. Read it live (Xcode console, Console, log), recorded (Instruments, Power Profiler, xctrace), or aggregated from users a day later (MetricKit, Organizer).
- Mobile production incident — the playbook
A build already on users’ phones cannot be recalled — pausing or halting a rollout only stops it reaching more people. So: detect per version, stop the spread (pause / halt), neutralise the bad path server-side (kill switch, compatibility shim, OTA JS rollback), ship a fix (hotfix + expedited review, then force-update), communicate, and learn in a blameless postmortem.
- Performance in production — field metrics, not lab numbers
The lab tells you whether a build can be fast; only the field tells you whether users’ devices are. The OS measures launch, hangs, hitches, memory, disk, CPU, battery and why the app died, aggregates it per day, and hands it to you (MetricKit) or to Apple (Organizer) / Google (Play vitals). Read percentiles per app version and device, never an average, and gate each release on them.
- Release-only bugs — when Debug lies
A Release build is a different program in a different environment: optimised code (no asserts, different interleavings, different observed object lifetimes), shrunk bytecode (R8), no dev flags (DEBUG, __DEV__), distribution signing with production entitlements and services, and no debugger slowing every thread. A bug that “only happens in prod” is a hidden assumption that one of these flips.
- Sanitizers & runtime checkers — make the bug crash here
Memory and threading bugs corrupt silently and crash later, elsewhere. Sanitizers are compiler instrumentation + a runtime that check every access as it happens and report the first bad access with the stacks that explain it. Runtime checkers — Main Thread Checker (MTC), Thread Performance Checker (TPC), exclusivity — need no special build. ASan and TSan cost 2–20× and their runtimes are not meant for production: Debug schemes, test plans, CI. Hardware memory tagging is the one built to ship.
- SwiftUI instrument · Cause & Effect · hitches & hangs
The SwiftUI template (Instruments 26+) times every SwiftUI update: lanes flag the long ones, Time Profiler shows what ran, the Cause & Effect Graph shows why. A hitch = a frame left on screen too long (one late refresh is enough); a hang = a discrete input (tap, key) left waiting on a busy or blocked main thread.
design
- API design — HTTP resources and Swift APIs
An API is a contract you can never fully take back: model resources (nouns) and let methods carry the verbs, make every write safe to retry, make every change additive, and judge a Swift API by clarity at the point of use. Old app versions live for years.
- Code smells → refactorings
Refactoring (Fowler): “a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behaviour”. A smell is a surface symptom that suggests a deeper problem — name the smell, name the refactoring, and keep behaviour pinned: tests first, tiny steps, commit each green step.
- Concurrency patterns — the shapes, and their Swift form
Every concurrent design answers two questions: who may touch this state (one owner + messages, or many + a lock) and what happens when one side is faster (a bounded buffer, backpressure, or dropping). The named patterns — producer–consumer, pool, actor, pipeline, fan-out/fan-in, reader–writer — are stock answers; Swift gives most of them a compiler-checked form (actor, TaskGroup, AsyncStream, Sendable).
- Data access patterns — under the Repository
A Repository is only the front door. Behind it: DTOs mapped to domain models at an anti-corruption edge, a local DB as the single source of truth the UI observes, a network gateway that only refreshes it, a unit of work committing changes together, a cache policy per data type, and cursors for paging. Offline-first: reads never wait for the network; writes go through an outbox.
- Dependency injection — roots, scopes, locators
DI = a type receives its collaborators instead of creating or finding them. The substance: where the graph is built (one composition root), how long each object lives (scopes; never long-lived holding short-lived), who may ask a container (only the root — anywhere else it is a service locator). Environment and @Dependency are ambient DI: handy, but the dependency leaves the init.
- Design principles — the rules beneath the patterns
Patterns trade indirection for changeability; these principles say what changeable code looks like: high cohesion, low coupling (named by kind — connascence), talk to friends, tell don’t ask, compose, one home per piece of knowledge, build only what’s needed, the right class for each responsibility (GRASP), dependencies toward stability.
- Functional design in Swift
Push decisions into pure functions over immutable values, push effects to a thin imperative shell, and use the type system (enums, smart constructors) so that illegal states cannot be written down. In Swift FP is a strong default, not a religion: local mutation of values is fine; the frameworks are object-oriented.
- GoF: Prototype · Composite · Bridge · Flyweight
Prototype (creational) — make a new object by copying a configured instance. Composite — leaf and group behind one interface, a tree the client walks uniformly. Bridge — split abstraction from implementation so two axes vary independently (M×N →M+N). Flyweight — share immutable intrinsic state, pass extrinsic state in. In Swift, value types + CoW are Prototype, and an enum holding [Self] is Composite.
- GoF: Visitor · Memento · Interpreter (+ Null Object)
Visitor — add operations over a stable set of element types without editing them, via double dispatch. Memento — capture an object’s state in an opaque snapshot so it can be restored (undo) without breaking encapsulation. Interpreter — one class per grammar rule; evaluate the AST. Null Object — a do-nothing implementation instead of nil checks. In Swift the first three usually become enum + exhaustive switch, value snapshots, and an indirect enum.
- Hexagonal · Onion · Modular monolith
Put the domain in the middle and make everything else — UI, HTTP, database, clock, push — a replaceable adapter plugged into a port the application defines. Hexagonal (Cockburn 2005), Onion (Palermo 2008) and Clean (Martin 2012) are one dependency rule in three vocabularies: source dependencies point inward. A modular monolith applies the same boundaries between modules in one deployable, before (or instead of) paying for microservices.
- iOS idioms and anti-patterns
Cocoa gives you a small set of communication idioms — delegate, data source, target–action, closure, NotificationCenter, KVO, responder chain — and choosing one is a question of how many listeners, whether the sender needs an answer, and who owns whom. Most iOS anti-patterns are one mistake: responsibilities and dependencies that nobody can see.
- Patterns already inside Apple’s frameworks
You use GoF patterns daily: the responder chain is Chain of Responsibility, target–action/UndoManager is Command (+ Memento), NotificationCenter/KVO/Combine are Observer, class clusters are Abstract Factory, appearance() is a Proxy, a ViewModifier a Decorator. Each row: pattern + API + mechanism + the gist.
- Swift idiom patterns — beyond GoF
Swift turns runtime patterns into compile-time ones: a phantom type/tagged ID makes a wrong argument a compile error, an enum makes an illegal state unrepresentable, a generic constraint is a Strategy chosen at build time — and type erasure is the price of going back to runtime. Order of preference: some/generics > any P<X> > a hand-written AnyX.
- The Composable Architecture (TCA)
Point-Free’s library for unidirectional Swift apps: a feature is a @Reducer — value-type State, an Action enum, a body that mutates state and returns Effects; a Store runs it; features compose by embedding child state/actions; the outside world comes in through @Dependency; TestStore proves every step. Current 1.26.2 (2026-08-28).
- Unidirectional data flow & state machines
State lives in one place; the view renders it and sends actions; a pure reducer computes the next state and returns effects (side effects as values) whose results come back as actions — one loop, one direction (Elm → Redux → TCA). A state machine constrains which transitions exist; statecharts add hierarchy, parallel regions and guards. Both aim at “make illegal states unrepresentable”.
- VIP · RIBs · MVI · Redux · MV — the architecture map
Every iOS architecture answers three questions: who owns the state, which way does data flow, and where do side effects live. VIP (Clean Swift) makes each screen a one-way cycle of three objects; RIBs (Uber) drive the app by a tree of business logic, not of views; MVI and Redux keep one immutable state changed only by a reducer; TCA is Redux made composable; MV says SwiftUI views plus @Observable models are already enough.
dev-tools
- tmux panes — split, move, resize, join, float
A pane is one pseudo-terminal running one program; panes tile a window, windows make a session, and one server process owns them all (socket in $TMUX_TMPDIR or /tmp), so detaching leaves every program running. Keys are the prefix C-b, then the key. Moving a pane moves the terminal itself — the program never restarts.
- Vim — the editing language: verbs, nouns, registers, undo
Normal mode is a language: ["x][count] operator [count] motion|text-object ("a2yy, ci", gUiw). An operator typed twice acts on the line (dd, >>); . repeats the last change; every motion is exclusive, inclusive or linewise. Registers are text, a macro is a register, undo is a tree. Same grammar in Vim 9.2 and Neovim 0.12.
engineering
- A/B testing statistics — power, peeking, SRM, CUPED
An A/B test is a hypothesis test on randomised groups. You fix α (false-positive rate), power 1-β (chance to detect the MDE if it is real) and the MDE before starting — together they fix the sample size. Then you prove the experiment is valid (SRM, exposure) before reading the effect, read it once at the planned horizon (unless the test was built for peeking), and report the effect with its confidence interval, not a bare p-value.
- Blue/green deployments
Run two identical production environments: blue serves users, the new version is deployed to idle green, tested there with no user traffic, then one switch (load balancer, Service selector, DNS, symlink) moves all traffic at once. Blue stays up, warm, as the instant rollback — but only the stateless tier is doubled: the database, queues and side effects are shared, so rollback is instant only if v1 still works with what v2 wrote.
- Dependency management — versions, lockfiles, choosing, updating
Every dependency is code you ship, cannot fully read, and must keep updating. Semver ranges say what you accept; the lockfile records what you got (every transitive package, exact version + hash) so every machine and CI builds the same tree. Choose libraries by maintenance, size, licence and exit cost, update in small automated steps, and remember that most of your tree is transitive — you are responsible for packages you never chose.
- Feature flags, experiments & mobile observability
Ship code dark behind a flag, turn it on for a hashed, random slice of users, log who was exposed, compare their metrics with control while guardrails (crashes, hangs, revenue) watch for harm, then ramp, hold or kill — without a new binary. On mobile this matters twice: a shipped build lives for months and the store rollout cannot be rolled back.
- Git in depth — objects, the DAG, merge vs rebase, bisect, branching
Git is a content-addressed object store plus movable pointers. A commit is a full snapshot (a tree) with pointers to its parent(s); history is the resulting DAG; a branch is just a ref naming one commit. Merge adds a commit with two parents (history kept); rebase re-creates your commits on a new base (new IDs, linear history) — which is why rebasing commits others already have breaks their clones.
- Large migrations — change the engine while the car is driving
A large migration (UIKit → SwiftUI, RN Old → New Architecture, Swift 5 → 6) succeeds when old and new coexist behind an adapter or interop layer, new code is written only the new way from day one, the work moves in small shippable steps (each behind a flag or per module, each with a rollback), progress and health are measured, and it ends by deleting the old path. Feature delivery never stops; a months-long rewrite branch is the failure mode.
- Lint & static analysis — where each check runs
A linter is a program that reads your source and reports patterns; syntax-only rules (SwiftLint lint, ESLint core, ktlint) are fast and run on every save, type-aware ones (SwiftLint analyze, typescript-eslint typed rules, detekt with type resolution) need a compile and run in CI. A formatter rewrites layout and ends style debate. What works is the pipeline: the right check at the cheapest stage, one blocking gate in CI, a baseline for old code, and a written suppression policy.
- OpenTelemetry for mobile — one trace from tap to database
OpenTelemetry (OTel) is the vendor-neutral standard for telemetry: an API you instrument against, an SDK that samples, batches and exports, the OTLP wire protocol and a Collector. A trace is a tree of spans sharing one trace-id; the app starts it at the user’s tap, and the W3C traceparent header carries it into every backend service — so one timeline shows where the 3 seconds went.
- Progressive delivery — rolling, canary, shadow, rings, staged rollouts
Expose a new version to users in steps, measure each step against a baseline, and promote or abort automatically — so a bad release hurts 1–5 % of traffic for minutes instead of everyone for hours. Deploy ≠ release: the binary can be everywhere while the feature is off.
- Release engineering — trains, versions, compatibility, hotfixes
A mobile release cannot be undone: every build is reviewed, signed, rolled out gradually, and then lives on phones for months. So releases leave on a fixed train (date fixed, scope floats), each build gets a strictly increasing build number, the backend stays compatible with every version still installed, a minimum-version switch exists before it is needed, and “rollback” means roll forward: a flag flip or a hotfix build.
- Store policy & platform deadlines — review, rejections, SDK minimums
Two gatekeepers with different levers. Apple reviews every build against the App Review Guidelines (90 % reviewed in < 24 h) and each spring requires the new Xcode/SDK for uploads. Google Play runs policy checks and yearly raises the target API level, now also 16 KB page-size support. Knowing the hot-spot guidelines, how to answer a rejection, and the dates on your calendar is part of senior release ownership.
- Tech debt & decision records — price it, pay it, write down why
Technical debt (Cunningham, 1992) is the extra cost future changes pay because of a shortcut taken — or a better design learned — earlier. Principal = the effort to fix it; interest = the extra effort (and risk) every change in that area pays until you do. Code nobody touches charges no interest. Manage debt like a portfolio: make it visible, price it in product terms, pay where interest is highest — and record why big decisions were made (ADRs) so nobody re-litigates them in a year.
- Typed contracts across iOS, Android, web & backend
Teams stop arguing about JSON when one machine-readable schema — OpenAPI, GraphQL SDL, Protobuf or JSON Schema — is the source of truth in version control: every client and the server generate their types from it, CI rejects breaking diffs, and contract tests prove the provider still serves what each consumer uses — a mismatch fails a build, not a user’s app.
- Zero-downtime database migrations
Every schema change must be tolerated by all code that is still running — the old pods of a rolling deploy, the blue stack you may roll back to, and app versions installed on phones for months. So a breaking change becomes expand → migrate → contract across several releases, data moves in small batches, and every DDL holds its lock for milliseconds.
ios-platform
- Accessibility & Localization
Accessibility: VoiceOver walks a tree of elements and speaks each one’s label, value, traits, hint; text must scale with Dynamic Type; honour user settings (Reduce Motion, contrast). Localization: every user-visible string is a whole sentence in a String Catalog, arguments are positional, plurals follow CLDR rules, layout is leading/trailing, and numbers/dates go through formatters.
- App Clips & Handoff / Continuity
Both ride on NSUserActivity. An App Clip is a small, separately built slice of your app that a URL (from a code, tag, link or map) launches without installing the app; Handoff moves your own current activity to your own nearby device (same iCloud account, BLE + Wi-Fi). Neither is a deep link, and neither is state restoration.
- App extensions — own process, shared disk
An extension is a .appex inside the containing app, launched by the system for a host app in its own process — own sandbox, bundle id, entitlements, a far smaller memory limit. It shares no memory with its app: they meet only in an App Group, a Keychain access group, or through the system.
- App Intents · Siri, Shortcuts, Spotlight, widgets (iOS 16 → 27)
App Intents (iOS 16+) exposes an app action to the system as plain Swift: a struct conforming to AppIntent with @Parameters and an async perform(). Write it once; Siri, Shortcuts, Spotlight, the Action button, interactive widgets, Control Center and visual intelligence all run the same type — no .intentdefinition file, usually no extension.
- App size & energy — thinning, ODR, what drains the battery
Size: the App Store slices one universal upload into per-device variants, asset packs move optional content out of the download, bitcode is gone. Energy: do less work, less often, in bigger batches, woken by events not timers, at the lowest fidelity the user accepts — the radio tail, GPS and wakeups cost more than bytes.
- Apple Pay in apps · PassKit payments
Apple Pay pays for physical goods and services with a Wallet card: the app builds a PKPaymentRequest, the system sheet authenticates, the Secure Element emits a DPAN + one-time cryptogram, Apple re-encrypts it to your merchant key, and the app forwards the opaque token.paymentData to your server → PSP. The app never sees a card number. Digital content used in the app is In-App Purchase, not Apple Pay.
- ARKit + RealityKit — tracking, anchors, entities
ARKit fuses feature points tracked across camera frames with the IMU (visual-inertial odometry) into a 6-DoF camera pose in a gravity-aligned world in metres; each tick is an ARFrame, and what it recognises (planes, images, faces, meshes) becomes anchors it keeps correcting. RealityKit renders on top: an Entity-Component-System engine (ARView in UIKit, RealityView in SwiftUI from iOS 18) drawing USD content locked to those anchors.
- AttributedString & rich text — model, editing, input
AttributedString (iOS 15) is a Swift value type: a sequence of characters plus a sequence of runs, each run a range with one AttributeContainer; attributes are type-safe keys grouped in scopes (Foundation, UIKit, SwiftUI, yours). NSAttributedString is the older reference type keyed by NSRange, still what TextKit stores. iOS 26 makes it editable in SwiftUI: TextEditor(text: $attributed, selection: $sel).
- AVFoundation — camera capture + audio session
AVCaptureSession is a graph: devices → inputs → session → outputs, configured and started on a private serial queue (startRunning() blocks), frames delivered on another serial queue, UI on main. AVAudioSession is policy, not playback: category + mode + options tell iOS whether you mix, duck, obey the silent switch, record, and keep playing in the background.
- Background execution
After the user leaves, an app gets a few seconds and is then suspended: in memory, no CPU. Every way of running later is either a short grant (beginBackgroundTask), a request the system schedules when it chooses (BGTaskScheduler, silent push), a hand-off to a daemon (background URLSession), or a declared mode that holds only while it is really in use (audio, location, …). None of them is guaranteed.
- CarPlay — entitlements, template scene, limits
A CarPlay app is not a separate target: it is a second scene (CPTemplateApplicationScene) of your iOS app, same process. You never draw its UI — you hand templates to a CPInterfaceController and the car renders them. Apple grants one category entitlement; the category decides which templates you may use and how deep the stack goes. Only navigation apps draw pixels (the map, in a CPWindow).
- CloudKit fundamentals — databases, zones, records, errors
Apple’s hosted database behind the user’s iCloud account. A container holds three databases — public (everyone, your quota), private (this user, their quota), shared (zones others shared with me). Records live in zones; a save is checked against the record’s change tag, so a conflict is an error you resolve, never a silent overwrite. Only custom zones give atomic writes, change tokens and sharing.
- CloudKit sync & sharing — CKSyncEngine, mirroring, CKShare
Three ways to sync: CKSyncEngine (iOS 17) — your store, the engine schedules push/fetch and you persist its state; NSPersistentCloudKitContainer (iOS 13) — Core Data mirrors itself into a zone, no sync code; SwiftData — the same mirror, private database only. Sharing: a CKShare in the owner’s private custom zone covers one record hierarchy or the whole zone; an accepted share shows up in the participant’s shared database, and their writes land in the owner’s zone.
- Core Animation — layers, actions, timing, GPU cost
A CALayer is a model object: a bitmap (contents) plus geometry and animatable properties — no events, no layout constraints. Each run-loop turn your changes are committed (layout → display → prepare → commit) to the out-of-process render server, which interpolates animations and composites every layer on the GPU. Speed = a cheap commit + as few GPU passes as possible (no needless blending, offscreen passes, copied or misaligned images).
- Core Data — contexts, merging & concurrency
A context is an in-memory scratchpad bound to one serial queue; it reaches SQLite through a coordinator whose row cache holds last-known row values. Contexts see each other’s work only after a save reaches the store and is merged in. Two saves of one row: optimistic locking detects it at save() and the saver’s merge policy decides — by default the save throws.
- Core Data — faulting, FRC, batch requests & persistent history
Fetched objects are faults, filled on first touch from the row cache or a SQL SELECT — performance = few round-trips. Batch requests run as SQL on the store: fast, but no context sees them until you merge the returned IDs. Persistent history logs every transaction (who, what) in the store, so each context, process and extension catches up from its own token.
- Core Data migrations & SwiftData
On open, Core Data compares the store’s recorded entity version hashes with the current model; if they differ it must migrate — lightweight (mapping inferred, schema-shaped changes only) or custom (mapping model + NSEntityMigrationPolicy code), one hop at a time. SwiftData (iOS 17) is a macro layer on the same engine: @Model classes, a ModelContext per actor, PersistentIdentifier across actors, VersionedSchema + SchemaMigrationPlan for the same lightweight/custom stages.
- Core Graphics — CGContext, paths, images, PDF
Core Graphics (Quartz 2D) is a C, CPU, immediate-mode 2D renderer. You talk to a CGContext — a state machine (CTM, clip, colours, line style, shadow, alpha, blend mode) with a stack you push/pop with saveGState() / restoreGState() — build a path, then paint it (fill / stroke), and the context rasterises into its destination: a bitmap, a view’s backing store, or a PDF (vectors kept). UIKit’s UIBezierPath, UIGraphicsImageRenderer and draw(_:) are thin wrappers over it.
- Core Image — lazy filter graphs on the GPU
A CIImage is a recipe, not pixels: applying a CIFilter only extends a lazy graph. Nothing is computed until a CIContext renders a rectangle of it — then Core Image walks the graph backwards from that rectangle (region of interest), concatenates adjacent kernels into as few GPU (Metal) passes as it can, and writes the result to a CGImage, pixel buffer, texture or file. Contexts are expensive — make one and reuse it; contexts and images are immutable and thread-safe, filters are mutable and are not.
- Core Location + MapKit
Core Location fuses GPS/Wi-Fi/cell into fixes under a permission the user can shrink any time (While Using/Always and Precise/Approximate); the right service is the cheapest one that answers the question. MapKit draws it: annotations = points (reused views), overlays = shapes (renderers).
- Core Motion — sensors, fusion, reference frames
Core Motion turns the accelerometer (g, gravity included), gyroscope (rad/s, biased) and magnetometer (μT, uncalibrated) into device motion by sensor fusion: attitude, gravity split from user acceleration, bias-free rotation, calibrated field. One CMMotionManager per app; the motion coprocessor also logs steps and activity while your app is not running (7 days).
- Deep links · Universal Links
A Universal Link is a plain https:// URL that opens your app only if the domain has proved, via its apple-app-site-association file, that it trusts your app ID; otherwise it opens the website. A custom scheme (myapp://) is unverified, can be claimed by any app, and fails when the app is missing. Every entry point should parse to one route and hand it to one router.
- EventKit & Contacts — access levels, model, sync
Calendars, reminders and contacts are private databases shared by every app. Climb the access ladder only as far as the feature needs: a system UI that needs no permission (EKEventEditViewController, CNContactPickerViewController) → a partial grant (.writeOnly events, iOS 17 · .limited contacts, iOS 18) → full access. One long-lived EKEventStore / CNContactStore; on “store changed”, refetch.
- Foundation — dates, calendars, formatters
A Date is an instant: a Double of seconds since 2001-01-01 00:00 UTC — no zone, no calendar, no locale. Calendar + TimeZone + Locale are the lens that turns it into a human day and does the arithmetic; formatters are the (costly) bridge to strings — POSIX/ISO 8601 for machines, localized styles for people.
- Foundation — the essential types
Most Foundation bugs come from doing by hand what a type already does correctly: build URLs with URLComponents, format numbers with a formatter/.formatted, convert with Measurement — and respect the sandbox lifecycle: Caches and tmp are purgeable, the container path changes, Data slices keep their parent’s indices.
- HealthKit — authorization, data model, queries, sync
HealthKit is an on-device, encrypted store shared by apps, reached via one long-lived HKHealthStore. Access is per type and per direction (read / share); read status is never revealed — a denied read looks like “no data”. Data = immutable samples; totals come from statistics queries (they de-duplicate iPhone + Watch), changes from observer + anchored ones.
- iPad windowing (iPadOS 26) & Mac Catalyst
In iPadOS 26 a scene can be a freely resizable window with Mac-style window controls, so an iPad app must lay out for any width and height, not a few Split View fractions — UIRequiresFullScreen is deprecated. Mac Catalyst recompiles the same UIKit scenes into a Mac app (title bar, NSToolbar, menu bar); Designed for iPad runs the iOS binary as is.
- Keyboard + text input
The keyboard belongs to the first responder: iOS shows its inputView (default: the system keyboard) + inputAccessoryView, and your layout moves — with keyboardLayoutGuide (iOS 15) or from the real end frame in the notifications. Input is shaped by traits, and is provisional while an IME holds marked text.
- Liquid Glass & new SwiftUI (iOS 26 · 27)
Liquid Glass is a system material for the functional layer (tab bars, toolbars, sheets, key controls) that floats above a full-bleed content layer; it lenses and adapts to what is under it. Standard components get it free with the Xcode 26 SDK; custom views opt in with .glassEffect(), grouped in a GlassEffectContainer so shapes blend and morph.
- Metal — device, pipelines, command buffers, frames in flight
Metal is Apple’s low-overhead GPU API. You build the expensive objects once — device, command queue, pipeline states compiled from MSL shaders, buffers, textures — and every frame record commands into a transient command buffer through encoders (render / compute / blit), commit() it, and the GPU runs it asynchronously while the CPU prepares the next frame. Correctness then hinges on one rule: the CPU must not overwrite data the GPU is still reading.
- Modern UIKit — observation, updateProperties, traits (iOS 17–26)
UIKit subscribes for you: an @Observable property (or a trait) you read inside an update method becomes a dependency; when it changes, UIKit invalidates only that view and re-runs only that method in the next update pass — no setNeeds…. On by default in iOS 26; iOS 18 opts in with UIObservationTrackingEnabled.
- Operation & OperationQueue
An Operation is a single-shot, KVO-observable unit of work; an OperationQueue starts it when isReady (every dependency isFinished), caps parallelism with maxConcurrentOperationCount, and drops it when it posts isFinished. Cancellation is a flag, dependencies are ordering only (no data), and an async subclass must drive its own state with KVO — or it never finishes.
- Photos — the picker vs PhotoKit, limited library
Two ways in. The out-of-process picker (PHPickerViewController 14, SwiftUI PhotosPicker 16) needs no permission — the app gets only the picked items. PhotoKit (PHPhotoLibrary, PHAsset, PHImageManager) is a live database behind authorization: .readWrite — which may come back .limited, a user-chosen subset (iOS 14) — or .addOnly. Picker unless you are a gallery, backup or editor app.
- Process death — “the OS killed the app mid-checkout”
A backgrounded app is suspended, and a suspended app can be killed without any callback (iOS jetsam, Android low-memory killer). When the user comes back it is a cold launch: everything in memory is gone, everything on disk / Keychain / restoration data survives — and the server may already have done the payment. So persist the screen and the draft before leaving, and make the operation idempotent so resuming can ask “did it happen?” instead of doing it twice.
- Push notifications (APNs)
Your server never talks to the phone: it POSTs JSON over HTTP/2 to APNs, addressed by a device token (one app install on one device, one environment) and authenticated by your key. The app only asks permission, obtains and uploads the token, and reacts to delivery.
- Real-time calls on iOS — WebRTC, CallKit, PushKit
A call is two planes: signalling (your server, any transport — usually a WebSocket — carrying SDP offer/answer and ICE candidates) and media (WebRTC: ICE finds a path through NATs with STUN, falls back to a TURN relay, then DTLS-SRTP encrypts audio/video peer-to-peer). On iOS the app is usually not running when the call arrives: a PushKit VoIP push wakes it, it must report the call to CallKit at once, and CallKit owns the system call UI and the audio session.
- Scenes, multiwindow + state restoration
Since iOS 13 one process drives many UI instances: each window is a UIWindowScene with its own lifecycle, backed by a persistent UISceneSession. The system may disconnect a background scene to save memory and reconnect it later; restoration hands the scene back its own NSUserActivity so it rebuilds UI state (ids, not model data) — unless a deep link says where to go.
- Screen Time API — FamilyControls · ManagedSettings · DeviceActivity
Three frameworks, one privacy trick. FamilyControls authorizes the app and lets the user pick apps/sites in a system picker that hands back opaque tokens — the app never learns which apps. ManagedSettings puts tokens into a store the system enforces (shields, restrictions). DeviceActivity wakes a monitor extension on schedules and usage thresholds. Usage data is shown only by a sandboxed report extension.
- SharePlay — Group Activities
SharePlay = your app’s activity shared over a FaceTime call or Messages conversation (and, iOS 17, AirDrop nearby). You define a Codable GroupActivity; one person activate()s it; the system hands a GroupSession to every participant’s sessions() stream; each app join()s and syncs through AVPlayer’s playback coordinator (media), GroupSessionMessenger (small messages) or GroupSessionJournal (files). All session data is end-to-end encrypted; there is no server of yours in the loop.
- SQLite internals for app engineers (+ GRDB)
SQLite is a library, not a server: one file of fixed-size pages (4096 B default) holding B-trees — one per table (rows by rowid) and one per index. Many connections may read, only one may write. In WAL mode commits are appended to -wal, readers keep a snapshot (end mark), and a checkpoint copies pages back. Core Data, SwiftData, GRDB and Android Room all sit on it.
- StoreKit 2 · in-app purchases & subscriptions
A StoreKit 2 purchase ends in a signed letter, not a callback: each Transaction is a JWS the App Store signs and StoreKit checks on the device, against the certificate chain packed inside it. Your part is verify → grant → finish() — with an ear open from launch (Transaction.updates) for all that is bought, renewed or refunded while you are not looking.
- TextKit 2 vs TextKit 1 — text layout on iOS
TextKit is the engine under UITextView and UITextField: a storage (the attributed text) → a layout manager → a text container (the shape to fill) → the view. TextKit 2 (iOS 15, default for UITextView since iOS 16) swaps glyph-based, whole-document layout for element/fragment objects laid out only around the viewport. Touching the old .layoutManager silently and permanently drops a text view back to TextKit 1.
- UICollectionView — compositional layout, registrations, configurations
A compositional layout (iOS 13) is declared, not computed in delegate callbacks: items sit in groups (the repeating unit), a group repeats along a section, sections stack into the layout. Every size is .absolute, .estimated or .fractional of its container. Cells are dequeued from registrations and rendered from content configurations (iOS 14).
- UIKit menus & interactions — UIMenu, context menus, menu bar
A menu is a value tree of UIMenuElements — UIMenu (a group) holding UIAction (a closure), UICommand (a selector sent up the responder chain) and UIDeferredMenuElement (loaded lazily). The same tree is shown by many presenters: a context-menu interaction (with a preview), a button, a bar item, the edit menu, the main menu bar (Mac; iPad since iPadOS 26).
- UIKit touches — hit-testing, responders, gestures, transitions
A touch goes down then up. On touch-down UIKit hit-tests: hitTest(_:with:) recurses from the window, frontmost subview first, and returns the deepest view whose point(inside:with:) is true — that view owns the touch for its whole life. Gesture recognizers on that view and its ancestors see the touch before the view does. Whatever is not handled — touches, key presses, nil-target actions — then walks up the responder chain via next.
- Video playback — HLS, ABR, AVPlayer in production
HLS = plain HTTP files: a multivariant playlist lists the same video at several bitrates, each variant is a media playlist of short segments (.ts or fMP4). The player measures throughput and buffer and switches variant at segment boundaries (ABR). In AVFoundation you watch state — AVPlayerItem.status, AVPlayer.timeControlStatus + reasonForWaitingToPlay — and tune startup, caps and buffer, never the download itself.
- Wallet passes · .pkpass, signing, updates
A Wallet pass is a signed zip (.pkpass): pass.json + images + manifest.json (SHA-1 of every file) + a PKCS #7 signature of the manifest made with your Pass Type ID certificate. Wallet surfaces it when relevant (time, place) and keeps it current via your web service: an empty APNs push says “changed”, the device pulls.
- watchOS & visionOS — the two other platforms
watchOS: a separate bundle on a separate device — glance-first, mostly suspended, talks to the phone through WatchConnectivity (four channels with different delivery guarantees) or the network itself. visionOS: SwiftUI scenes placed in space — windows, volumes, immersive spaces — driven by gaze + pinch, where the system, never the app, knows where the user looks.
- WidgetKit · Live Activities · Dynamic Island
A widget is not a live view: a separate extension process hands WidgetKit a timeline of pre-rendered entries, the system swaps them at their dates and decides when to ask again (budgeted). A Live Activity is the same WidgetKit/SwiftUI surface fed by ActivityKit state updates — local or by APNs push — for a bounded event (8 h).
ios-swift
- App & view-controller lifecycle — exact order
A VC’s view is lazy: first access to .view runs loadView then viewDidLoad (once); every show runs viewWillAppear → viewIsAppearing → layout → viewDidAppear; every hide runs viewWillDisappear → viewDidDisappear; deinit last. The app moves Not running → Inactive ⇄ Active → Background → Suspended, reported per scene since iOS 13.
- ARC · strong / weak / unowned · capture lists
ARC = the compiler inserts retain/release; an object is freed deterministically the instant its strong count hits 0 (deinit runs). No tracing GC ⇒ no cycle detection: two objects that strongly own each other leak forever, silently. You break cycles by making the back-edge weak or unowned.
- Auto Layout · priorities · UIStackView · self-sizing cells
Every constraint is one linear equation item1.attr {=,≤,≥} multiplier × item2.attr + constant — the engine solves them all so each view gets exactly x, y, width, height. Too few = ambiguous; contradictory required ones = unsatisfiable. Priorities decide who yields: 1000 / 750 / 250.
- Combine in depth — protocols, demand, subjects, schedulers, lifetimes
A Publisher is a recipe; subscribe(_:) makes it create a Subscription and hand it to the Subscriber, which requests a demand. The publisher may send at most that many values, then one completion. Demand is Combine’s backpressure — but sink/assign ask .unlimited, so a push source that outruns its consumer must drop or buffer.
- Combine operators · errors · sharing · moving to async/await
Every operator is a struct deciding which values it emits, how it passes demand upstream and when it ends. One failure ends the whole chain unless caught inside a flatMap; share() gives one upstream many subscribers. Migrating keeps Combine at the edges: .values / Future.value in, a cancellable Task for the token.
- Concurrency · GCD · async/await · actors
GCD submits closures to queues and blocks threads to wait; Swift Concurrency suspends tasks at await (the thread is freed) and lets the compiler prove safety with actors (serialised state), @MainActor (UI) and Sendable (what may cross). Rule zero in both: UIKit only on the main thread.
- Instruments · measure-first performance workflow
Measure, don’t guess: baseline on a real device in the Release/Profile config → pick the instrument that answers this symptom → change one thing → re-measure the same scenario. For each tool know its name, how to read its number, and what it cannot see.
- Locks & synchronisation primitives — Apple platforms
A lock makes a critical section mutually exclusive and has an owner (the thread that took it, which must release it); a semaphore is a counter with no owner; a serial queue or actor serialises by ownership instead. Pick by: is there an await inside? how short is it? do you need a count? Then: never block the cooperative pool, never hold a lock across a call-out.
- Navigation & presentation — push vs present
Push adds a VC to a UINavigationController’s viewControllers array (drill-down, back button, pop). Present starts a separate presentation chain linked by presentedViewController / presentingViewController (a modal task you finish with dismiss). The modalPresentationStyle decides whether the presenter’s view leaves the screen — and so whether it gets viewWillDisappear/viewWillAppear.
- Observation · Combine · cancellables
Four ways to observe on iOS — NotificationCenter (broadcast bus), KVO (one NSObject property), Combine (typed streams + operators + demand), @Observable (per-property read tracking, iOS 17). Every one hands you a lifetime object; what matters is who owns it and whether the closure owns you back.
- Persistence — pick the store, respect the context
Secrets → Keychain; small settings → UserDefaults; blobs → files in the right sandbox directory; a queryable object graph → Core Data / SwiftData; recomputable in-memory → NSCache. In Core Data every NSManagedObjectContext is bound to one queue: touch it and its objects only inside perform, and hand NSManagedObjectIDs — never objects — across queues.
- Protocols, generics & method dispatch
A protocol is a contract; an extension adds shared behaviour. Only requirements (declared in the protocol body) go into the witness table and dispatch dynamically — a method that lives only in the extension is picked statically from the declared type. some P = one hidden concrete type (static); any P = a box holding any conformer (dynamic).
- SwiftUI state & data flow
A view is a cheap struct rebuilt constantly; its state lives outside it in SwiftUI’s storage, keyed by view identity. The only question each wrapper answers is who owns the truth: this view (@State, @StateObject) or someone else (@Binding, @ObservedObject, @EnvironmentObject).
- Table views, cell reuse & diffable data source
A list keeps only the visible cells alive and recycles them — so a dequeued cell is used, never blank. A diffable data source replaces index math: you describe the whole desired state as a snapshot of unique Hashable IDs, apply it, and UIKit computes the inserts/deletes/moves.
- URLSession & networking
URLSession moves bytes; you judge them: it throws only on transport failure — a 404/500 arrives as success, so check the status, then decode. Three layers, three error types, and UI back on the main thread.
- Value vs reference · mutating · copy-on-write
A value type (struct, enum, tuple) is copied on assignment / argument passing — every variable owns an independent value. A reference type (class, actor, closure) is shared — assignment copies the pointer, all variables see one object with an identity (===). Default to struct; reach for class when you need identity.
iot
- CoAP & LwM2M — REST and device management for constrained devices
CoAP (RFC 7252, 2014) is REST over UDP: methods and HTTP-like codes in a 4-byte binary header, per-message reliability (CON + ACK, back-off), push by Observe, big bodies block-wise, security by DTLS (per hop) or OSCORE (end to end). LwM2M (OMA SpecWorks) is device management on CoAP: a numbered Object / Instance / Resource tree on the device (/3/0/3 = firmware version) plus bootstrap, registration, management and reporting.
javascript
- Async JavaScript — promises, await, combinators, cancellation
A promise is a settle-once result: its executor runs now, its handlers always later, each as a promise job (a microtask on the web). then returns a new promise that adopts whatever its handler returns; async/await runs on the same jobs. The work starts when it is called and a promise cannot be cancelled — an AbortSignal asks the work to stop.
- Functional idioms — currying, composition, copies, lazy iterators, tags
Functions are values: pass them, return them, let them close over state. Build behaviour from small functions over values you do not mutate: currying and partial application fix arguments, pipe chains steps, toSorted / with copy instead of mutating, iterator helpers pull one value at a time, and a tagged template is a function call on a template’s pieces.
- Prototypes, objects and classes
Every object has a hidden [[Prototype]] link; a read that misses its own properties walks the chain to null — objects delegate at run time, nothing is copied. A write lands on the object itself unless a setter or a read-only property up the chain says no. class wires the same chain and adds real semantics: new-only, fields, #private, super.
- Scope, closures and this
Scope is lexical: fixed by where code is written. Every function keeps [[Environment]], the Environment Record it was created in; a closure is that link keeping bindings (not values) alive. this is dynamic: set by how the function is called and looked up in the nearest record that has one — arrows have none, so they see the enclosing this.
- Types, coercion and modules
Seven primitive types (immutable, by value) + Object (by identity). Implicit conversions are built from ToPrimitive, ToNumber, ToString, ToBoolean, so every “WAT” traces. ES modules link the whole graph before any code runs and imports are live bindings; require runs a file and returns an object.
linux
- Containers = namespaces + cgroups + overlayfs
A container is an ordinary Linux process on the shared host kernel: namespaces limit what it can see, cgroups limit what it can use, capabilities + seccomp + an LSM limit what it may do, and an overlayfs root built from read-only image layers is what it stands on. No hypervisor, no guest kernel — a kernel bug is an escape.
- Linux boot — firmware to login, and how to break in
Firmware (UEFI) runs a loader from the ESP; the loader loads the kernel + initramfs and hands over a command line; the initramfs makes the real root reachable (drivers, LUKS, LVM), mounts it and switches root to systemd as PID 1, which walks targets to default.target. Secure Boot checks each stage’s signature; the TPM records each stage’s hash.
- Linux filesystems & storage — VFS, page cache, durability
A file descriptor indexes the process’s fd table → an open file description (offset, status flags) → an inode (metadata + block map, no name); dentries map names to inodes. write() only dirties the page cache; data is durable after fsync(), and a file is replaced atomically by write tmp, fsync, rename, fsync the directory.
- Linux memory — accounting, reclaim, swap, OOM
Idle RAM is lent to the page cache, so “free” is always small; the number that matters is MemAvailable. Under pressure the kernel reclaims — drops clean file pages, writes dirty ones, swaps anonymous ones — first in the background (kswapd), then inside the allocating task (direct reclaim, a stall); when reclaim stops making progress it OOM-kills the task with the highest oom_score, system-wide or inside the cgroup that hit memory.max.
- Linux networking stack — packet path, netfilter, routing
A frame is DMA’d into a ring, polled by NAPI in softirq, offered to XDP, merged by GRO, copied to taps, run through tc and the netfilter hooks; a routing decision sends it up to a socket (INPUT) or across (FORWARD). conntrack remembers every flow, so NAT is decided on the first packet and replies are reversed for free. DNAT before routing, SNAT after.
- Linux performance — USE, the first 60 seconds, perf, eBPF, PSI
Start from resources, not guesses: for every resource check Utilization, Saturation, Errors (USE) with fixed first-minute counters; then profile (perf samples stacks → flame graph) or trace (eBPF: in-kernel, aggregated, cheap). Know what each number counts — Linux load includes D-state tasks, wa is idle time, %util cannot see parallelism, PSI measures stalls directly.
- Linux security — credentials, permissions, capabilities, LSMs, sudo, SSH
The kernel decides every access from the calling thread’s credentials: seccomp filters the syscall at entry, DAC (mode bits + ACL, against the fsuid) says yes or no, a capability may override a DAC “no”, and the LSMs (SELinux, AppArmor, Landlock, Yama …) can, by design, mostly only add a “no”. Root is uid 0 plus a full capability set — both can be taken away. sudo, run0, PAM and sshd are the user-space doors that hand them out.
- systemd — units, dependencies, services, sandbox, journal
systemd (PID 1) turns unit files into a transaction of jobs on two independent axes — requirement (Wants, Requires: what starts) and ordering (After, Before: when) — and gives each service its own cgroup to limit, log and kill all its processes.
macos
- macOS power-user CLI — what each command really talks to
Most macOS admin commands are thin clients of a daemon that owns and caches the state — so change it through the tool, name the domain (prefs domain, launchd gui/<uid>, log subsystem), and expect SIP, TCC and the sealed system volume to refuse even root.
- macOS security architecture — boot, seal, first launch, runtime
Each layer catches what the one before cannot: Secure Boot starts only an Apple-signed macOS, as its LocalPolicy allows; SIP keeps the sealed system volume (SSV) read-only even for root; a quarantined download meets Gatekeeper (signature, Developer ID, notarization, XProtect) at first open; then the hardened runtime blocks injection, the App Sandbox confines, TCC asks per resource, FileVault encrypts. macOS 27 (Sep 2026): Apple silicon only.
- XNU, launchd & XPC — how macOS runs your code
XNU is a hybrid kernel: CMU’s Mach (tasks, threads, ports, VM, scheduler), BSD code from FreeBSD (processes, POSIX, VFS, sockets, signals) and IOKit (C++ drivers) in one address space. The kernel starts launchd as the first process; launchd owns every service name, holds its port, and starts the job when the first message arrives. XPC is launchd-managed IPC on top — how an app splits into small, separately sandboxed, crash-isolated helpers.
networking
- Certificate pinning in 2026 — when, what, and how not to brick
Pinning adds an app-level rule on top of normal validation: the verified chain must contain a public key you chose (its SPKI hash). It stops a mis-issued, compelled or user/MDM-installed CA from intercepting you — and turns any unplanned key change into an outage only an app update fixes. Android calls it “not recommended”, Apple “not required”; CT and CAA now cover most of the mis-issuance risk. Pin only when the threat model demands it, and then with backups.
- Data transfer optimisation — fewer bytes, fewer times
The cheapest byte is the one never sent. Work down the ladder: don’t send (cache, 304), send less (fields, pages, deltas), encode smaller (binary, no names), compress (brotli / zstd / gzip), right-size media (pixels you display, modern formats), and adapt to the link (HLS). On mobile, fewer requests matter as much as fewer bytes: every one costs RTTs and radio time.
- DNS for app developers — resolution, records, caching, IPv6-only
DNS maps a name to records through a hierarchy: your device’s stub resolver asks a recursive resolver, which walks root → TLD → authoritative and caches every answer for its TTL. Classic DNS is plaintext UDP/53; encrypted DNS (DoT/DoH) hides it, DNSSEC authenticates it. On iOS the app must work on IPv6-only networks (NAT64/DNS64) — App Review tests it.
- Engineering for bad networks — offline, flaky, captive, metered
On a phone the network is a variable: it vanishes (tunnel), degrades (one bar, 20 % loss), lies (a captive portal answers every request with a login page), costs money (cellular, Low Data Mode) and changes under you (Wi-Fi → LTE). Give every request a timeout, a retry rule, an idempotency story and an offline behaviour — then prove it under a simulated bad network.
- GraphQL on iOS — Apollo iOS 2.x
GraphQL is a typed query language over one endpoint: the server publishes a schema, the client sends an operation naming exactly the fields it wants (+ typed variables), and gets back JSON of the same shape as {data, errors}. Apollo iOS generates Swift types from your .graphql files and keeps a normalised cache: every object with a cache ID is stored once, so every query that contains it sees the same, updated value.
- gRPC & Protocol Buffers — wire format, evolution, HTTP/2
Protocol Buffers is a schema-first binary encoding: every field travels as (field number, wire type) + value — names never do, so the field numbers are the contract. gRPC is RPC over HTTP/2: POST /pkg.Service/Method, length-prefixed protobuf messages on one stream, the result in trailers (grpc-status); unary + three streaming kinds, deadlines built in.
- HTTP/1.1 · HTTP/2 · HTTP/3 — and the headers that matter
One set of semantics — methods, status, headers, written once for all versions in RFC 9110 — on three wire formats, each built because the queue moved down a layer: 1.1 queues requests on a connection, 2 multiplexes streams over one TCP pipe that a single lost packet stalls, 3 gives every stream its own pipe inside QUIC over UDP.
- NAT, IPv4 & IPv6 — what sits between the app and the server
IPv4 ran out, so a phone sits behind NAT — often two (home router + carrier CGNAT) — which rewrites the private source IP:port to a shared public one and keeps a mapping table. Only outbound packets create rows, so nobody can dial in: P2P breaks, yet it is not a firewall. IPv6 gives every device global addresses (no NAT); IPv6-only carriers reach IPv4 servers via NAT64/DNS64.
- Network performance on cellular — radio states, round trips, reuse
On cellular a small request is dominated not by bytes but by waking the radio (promotion from idle: ∼0.1–0.3 s on LTE, up to 2 s on 3G, then a tail of seconds at high power) and by round trips: DNS + TCP + TLS before the first byte, each one cellular RTT. So: fewer, earlier, bigger requests over connections you already have — and measure the phases, not the total.
- Network.framework on the LAN — Bonjour, Local Network
Network.framework (iOS 12) is Apple’s socket API: an NWConnection is one flow driven by a state machine on your queue, an NWListener accepts flows and can advertise a Bonjour service, an NWBrowser discovers services as endpoints the connection resolves later. Local-network traffic is gated by the Local Network privacy alert (iOS 14) — with no API to read its state. iOS 26 adds async NetworkConnection / NetworkListener / NetworkBrowser.
- OAuth 2.0 · OIDC · JWT — for a native app
OAuth 2.0 (RFC 6749) is delegated authorization: the app gets a scoped access token without ever seeing the password. OIDC adds authentication: an ID token saying who logged in. A native app is a public client (no secret), so it uses authorization code + PKCE (RFC 7636) in the system browser (RFC 8252). A JWT (RFC 7519) is signed, not encrypted.
- Resumable & chunked uploads — from a phone that keeps losing signal
A big upload over a mobile network will be interrupted. Resumable: the server keeps the bytes it has under an upload URL and reports its offset; after a drop the client asks “where were we?” and continues from there. Chunked / multipart: the file is split into parts that are sent, retried and checksummed independently, then assembled by an explicit complete. On iOS a background URLSession hands the transfer to a system daemon — from a file, never from Data.
- TCP · UDP · QUIC — handshakes, windows, and why QUIC exists
TCP turns lossy IP packets into one reliable, ordered byte stream: a 3-way handshake agrees on sequence numbers, ACKs + retransmission recover loss, the receive window protects the receiver (flow control), the congestion window protects the network. UDP is ports + checksum and nothing else. QUIC rebuilds TCP’s guarantees per stream on UDP with TLS 1.3 inside — 1-RTT setup, no cross-stream head-of-line blocking, survives an IP change.
- TLS 1.3 & PKI — handshake, trust, pinning
TLS gives confidentiality (AEAD), integrity and server authentication: an ephemeral ECDHE exchange makes the keys (forward secrecy), and a certificate chain ending in a root the device already trusts proves the key belongs to the hostname. TLS 1.3 (RFC 8446) does it in 1 RTT; resumption can send data in 0 RTT — replayable.
- TLS 1.3 in depth — key schedule, records, resumption, ECH
TLS 1.3 (RFC 8446) feeds its input secrets — a PSK and the ECDHE result — through three HKDF-Extract stages (Early → Handshake → Master); every key is an HKDF-Expand-Label of one of them bound to the transcript hash, so each phase and direction has independent keys. Records are AEAD-sealed with a per-record nonce. A ticket makes a PSK for resumption; 0-RTT data is replayable; ECH hides the SNI.
- WebSockets & realtime on iOS
A WebSocket (RFC 6455) is an HTTP/1.1 request that upgrades (101) into a full-duplex stream of small frames on the same TCP connection. It gives foreground realtime; it does not give delivery across reconnects, ordering across connections, or life in the background — you build heartbeats, resubscribe, gap fill and dedup, and use APNs when the app is not running.
- What happens when you tap a URL — end to end, in round trips
Before the first response byte, the phone may have to wake its radio, resolve the name, open TCP, negotiate TLS and send the request — each step costs a network round trip (RTT). Cold over TCP + TLS 1.3: 4 RTT + server time; HTTP/3: 3; a reused connection: 1. Every latency trick removes one of these rows.
os
- iOS security model — sandbox, entitlements, code, IPC, memory, keys
Every third-party app runs as user mobile, sandboxed in its own container; anything more is an entitlement — a key–value pair signed into the app and allowed by its profile. Only Apple-signed code runs, libraries must share the app’s Team ID, writable+executable memory is Apple-only. Other processes are reached over Mach/XPC; data at rest is encrypted under keys tied to the device UID and the passcode; the silicon adds PAC, page-table monitors, memory tagging.
- Mach-O & dyld — the file, the fixups, the loader
A Mach-O is a header, a list of load commands (what to map, which dylibs, where main is, the signature) and the segments they describe. The kernel maps the executable and dyld; dyld loads every dependent dylib, writes fixups into DATA — rebase (add the ASLR slide) and bind (another image’s symbol) — runs initializers bottom-up and calls main. Code (__TEXT) is never written: calls into a dylib go through a stub that loads a pointer from DATA.
- OS fundamentals — processes, threads, virtual memory, syscalls
A process = an address space + resources (fds, credentials, signal dispositions) with ≥1 thread (registers + stack, the unit the scheduler runs). The kernel shares CPUs by scheduling, maps each process’s virtual pages to physical frames through page tables (cached in the TLB), fills them lazily on page faults, and is entered only by a system call, an exception or an interrupt.
- ZFS — pools, copy-on-write, checksums, snapshots
ZFS is a volume manager and a filesystem in one: disks form vdevs, vdevs form a pool, and every dataset draws space from the whole pool. Nothing is overwritten in place — every change is written to new blocks and the tree of checksummed block pointers is re-rooted atomically, so a crash leaves the old or the new state, a snapshot is free, and silent corruption is detected and, given redundancy, repaired.
react-native
- Android ANRs & native crashes — for RN developers
An RN app on Android fails in five ways — fatal JS error, JVM exception, native signal in a .so, ANR (main thread blocked 5 s on input), silent kill. Each leaves a different record read by a different tool.
- Android for React Native developers
android/ is an ordinary Gradle project embedding a JS bundle: AGP compiles Kotlin/Java (R8 shrinks it), the NDK builds C++ per ABI, the manifest merger combines every library’s manifest, you sign with an upload key and Play re-signs. Most Android “RN bugs” are manifest, permission, SDK-level or R8 problems.
- Auth & sessions in React Native
The protocol is the native one — authorization code + PKCE in the system browser (ASWebAuthenticationSession / Custom Tabs). The RN work is: a library that does it right, refresh token in Keychain/Keystore, access token in memory, one refresh at a time for every caller, and a logout that wipes every cache the user’s data reached.
- Background work in React Native
RN has no background scheduler of its own: JS runs only while the native process is alive and not suspended. Every background feature is a native scheduler — BGTaskScheduler, WorkManager, a push, a background mode — that wakes the app and boots or resumes the JS runtime for a short, OS-chosen window. The OS picks when; your code only picks what.
- Environments, config & secrets in React Native
An environment (dev / staging / prod: API host, ids, keys) is chosen at build time — Android productFlavors, iOS configurations + schemes, or Expo’s app.config + EAS environments. Every value that reaches JS or a native resource is inside the binary; only values read by the build itself (signing, uploads) stay secret.
- Error handling in React Native
Every failure has one catcher: a render error goes to the nearest error boundary; an uncaught JS exception to ErrorUtils’ global handler (fatal in release = crash); an unhandled rejection to nobody unless you install a tracker; a native crash, an ANR or OOM kills the process and is reported next launch. Design which errors the user sees, which retry, and which crash on purpose.
- Hermes & Hermes V1 — bytecode, Hades, source maps
Hermes is Meta’s JS engine built for RN start-up: the release build compiles JS to bytecode (.hbc) with hermesc, so the phone mmaps and interprets it — no parse, no compile, small heap. Default since RN 0.70; the built-in JSC left core in 0.81. Hermes V1 — new compiler + VM — was opt-in in 0.82 and is the default since 0.84; it does not yet include native (“Static Hermes”) compilation or a JIT.
- iOS for React Native developers — the native half
The iOS app is an ordinary Xcode project whose dependencies come from CocoaPods (pod install turns node_modules podspecs into Pods.xcodeproj), whose build phases bundle your JS, and whose Info.plist, entitlements, privacy manifest and signing are yours to get right — most “RN build errors” are one of those phases failing.
- Metro — how the React Native bundler works
Metro turns an entry file into one JS bundle + source map in three stages: resolve every import into a dependency graph, transform each module with Babel in parallel workers (cached per file), serialise the modules as __d(factory, id, deps) definitions plus polyfills and a __r(entry) call. In development it is also the server on :8081, pushing changed modules over a WebSocket for Fast Refresh.
- Native modules — TurboModules, Fabric, Expo Modules
A typed TypeScript spec is the contract; Codegen turns it into C++/ObjC++/Java glue; at runtime JS holds a JSI host object and calls straight into C++ and on to Swift/Kotlin — no JSON bridge, sync possible, modules lazy-loaded.
- React 19 · 19.2 · React Compiler — Actions, use, Activity, auto-memo
React 19 (Dec 2024) makes async updates first-class: an Action is a function run in a transition, and React tracks its pending, optimistic and error state (useActionState, useOptimistic). 19.2 (Oct 2025) adds <Activity> and useEffectEvent; React Compiler 1.0 (Oct 2025) memoises components and hooks at build time. RN: React 19.0 in 0.78, 19.1 in 0.80, 19.2 in 0.83.
- React hooks — the mechanisms
Hooks are slots on the fiber, matched by call order. Each render is a snapshot its closures capture. Effects sync with the outside world after commit; memo hooks keep identity. Most bugs: an old snapshot, or a dep with a new identity every render.
- React Native 0.82 → 0.87 — what changed, release by release
A minor about every two months; the current and the two previous minors are supported. 0.82 (Oct 2025) runs only the New Architecture; later releases remove the legacy code, make Hermes V1 and prebuilt iOS binaries the default (0.84), share one animation backend (0.85), and generate a strict TypeScript API from source (0.87). 0.83 and 0.86 shipped no user-facing breaking changes.
- React Native accessibility — props, platforms, testing
VoiceOver and TalkBack read the native view tree, not your JSX: RN maps each prop onto UIAccessibility (iOS) or AccessibilityNodeInfo (Android). Prefer the web-aligned role + aria-* props (role wins over accessibilityRole); a few needs stay platform-specific — live regions are Android-only, iOS uses announcements; modal scoping is iOS-only.
- React Native app security — the binary is public
Everything you ship — JS bundle, Hermes bytecode, Info.plist, BuildConfig — is readable by anyone who downloads the app, and on a rooted/jailbroken phone the attacker also controls your process at runtime. So: no secrets in the client, tokens only in Keychain/Keystore, raise the cost (pinning, R8, RASP), and let the server decide.
- React Native architecture — Bridge vs New Architecture
React runs on a JS thread; real native views live on the UI thread. The legacy Bridge joined them with async, batched JSON; the New Architecture (default since RN 0.76) uses JSI — JS calls C++ directly, sync or async — with the Fabric renderer and lazy, typed TurboModules generated by Codegen.
- React Native CI/CD & Android signing — build once, promote
An RN pipeline is two native builds (iOS on macOS, Android on Linux) around one JS codebase, plus an OTA lane for JS-only changes. Make it fast with lockfile-keyed caches, reproducible with signing secrets in the CI store (Android keystore, iOS via match/API key), and safe by promoting the tested artifact — never rebuilding for release. On Android you sign with an upload key; Google re-signs with the app signing key it keeps.
- React Navigation — navigators, nesting, deep links
Navigation is a tree of navigators holding one serialisable state object; actions (navigate, goBack) bubble up to the nearest navigator that can handle them, deep links are parsed down into that state, and screens stay mounted under a push — so “appear” is focus, not mount.
- Rendering & reconciliation — React on React Native
A render calls your components to produce a new element tree; reconciliation diffs it against the current fiber tree by type + key; only the differences are committed — on RN as a new Fabric shadow tree that is laid out (Yoga) and mounted as native-view mutations. Re-render ≠ native update.
- RN animations & gestures — Animated, Reanimated, RNGH
Smooth animation means computing each frame on the UI thread, so a busy JS thread cannot drop it. Animated’s useNativeDriver does this for a pre-declared animation of transform/opacity; Reanimated runs your own worklets on the UI thread; Gesture Handler recognises touches natively and feeds them. iOS analogue: Core Animation keeps running while your code blocks.
- RN app size — what one device downloads, and the levers
Users download a per-device slice: from an AAB, Play builds split APKs (base + one ABI + one density + the device’s languages); the App Store thins iOS uploads. In RN the heavy part is native libraries × ABIs (Hermes, libreactnative.so, every native dependency), then assets. Measure download size.
- RN debugging toolchain — which tool sees which layer
React Native DevTools (Chrome DevTools frontend, default since 0.76) debugs the JS + React layer of a debug build; everything below JSI — C++, Kotlin/Swift, the OS — is Xcode / Android Studio territory, and release builds are debugged with profilers, logs and symbolicated crash reports. Name the layer first, then the tool.
- RN memory leaks — two heaps, retainers, images
A leak is unwanted reachability from a GC root after the screen that needed it is gone. RN has two memories: the Hermes JS heap (DevTools heap snapshots) and native memory (views, bitmaps, modules — Xcode / Android Studio only). Proof is a staircase: the same growth on every repeat of an action.
- RN performance — two budgets, lists, re-renders, startup
An RN app drops frames on two independent threads: the JS thread (React render, business logic, JS-driven animation) and the UI/main thread (native layout commit, drawing, native animation). Each gets 16.7 ms per frame at 60 Hz (8.3 ms at 120 Hz ProMotion). Find which thread is late, prove it with a profiler on a release build, then apply the cheapest fix.
- RN startup — phases, what cuts each, how to measure
A cold start runs native init → JS runtime → bundle load → module factories (the top-level code of every imported module) → first render/mount = TTID → real content = TTFD/TTI. Every optimisation is “do less before the first frame”: precompiled bytecode, lazy modules, a thin root, deferred SDKs. Measure it on a release build on a low-end Android.
- RN state & data — the taxonomy, and the tool for each kind
“Which state library?” is the wrong question. Classify first — server, navigation, local UI, shared client, form, persisted (secret?) — each has a best-fit tool; most bugs are one kind kept in another’s tool.
- RN testing + TypeScript
Buy confidence per second: TS strict for free, Jest for logic, the bulk in RNTL component tests that query like a user against mocked network, and a few E2E journeys — Detox (grey-box) or Maestro (black-box).
- Tooling & release — Expo, EAS, OTA, Metro, native builds
An RN app is a native binary (reviewed, signed, store-shipped) that runs a JS bundle made by Metro. Change native code ⇒ new store build; change only JS/assets ⇒ an OTA update may replace the bundle — but only for binaries with the same runtimeVersion.
recall
- Named facts — the numbers, names and lists of iOS development
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.
runtime
- JS engines — JIT tiers, shapes, inline caches, GC
An engine turns source into bytecode, interprets it while recording feedback (maps, types, call targets) and compiles hot functions in tiers that speculate on that feedback — a failed guard deoptimises to the bottom tier. Objects share hidden classes, so an inline cache turns o.x into one compare and one load. Memory is a tracing, generational GC: what is reachable lives.
- Node.js runtime — libuv, streams, processes, releases
Node = V8 (runs JS, GC) + libuv (event loop, the kernel’s poller for sockets, a 4-thread pool for files, dns.lookup, crypto, zlib) + C++ bindings. Your JS runs on one thread per isolate — block it and every request waits.
- The JavaScript event loop — browser and Node
One thread runs JS to completion. The browser takes one task from a queue of its choosing, runs it, then drains every microtask; painting is a task of its own, queued at each rendering opportunity. Node walks libuv’s phases and, after every callback, drains process.nextTick, then microtasks. Nothing runs between two microtasks — an endless chain of them freezes everything.
security
- Ad privacy — App Tracking Transparency & AdAttributionKit
Two different systems. ATT is a permission for tracking — linking data from your app with other companies’ data for ads or ad measurement, or sharing it with a data broker; unless the user taps Allow, the IDFA is all zeros. AdAttributionKit (iOS 17.4+, successor of SKAdNetwork) is measurement without permission: the device picks the winning ad and sends a delayed, signed, crowd-anonymised postback with no user or device ID.
- Deep-link attack surface — hijacking, validation, PKCE
A deep link is a request from a stranger: any app, web page, QR code, SMS or push can fire it with any parameters. A custom scheme proves nothing — another app can register it and receive your links. A Universal Link / App Link proves the destination (your domain names your app), never the sender. So: parse and allowlist every parameter, confirm every action, carry no secrets — and protect OAuth redirects with PKCE.
- Device attestation — App Attest, DeviceCheck, Play Integrity
Attestation lets your server ask the platform vendor “is this request coming from my genuine, unmodified app on a genuine device?”. App Attest makes a Secure-Enclave key, has Apple attest it once, then the app asserts (signs) each sensitive request with it; Play Integrity returns a Google-signed verdict about app, device and account. Both are evidence for a server-side risk decision — not authentication, not a jailbreak detector.
- iOS reverse engineering & tampering — the defender’s view
A shipped app runs on a device its owner controls. The IPA is a zip, the Mach-O lists every class and string, App Store FairPlay encryption only stops copying (the code is decrypted in memory to run), and Frida rewrites any function at runtime — so jailbreak checks, pinning and anti-debugging are costs you impose, not boundaries. Assume the client is compromised: secrets and decisions live on the server.
- JWT attacks & token hardening — RFC 8725, DPoP, RFC 9700
Every classic JWT break is the verifier trusting the token to describe how to verify itself: the header’s alg, kid, jku, jwk are attacker input. Fix: the server decides algorithm, key and token type (RFC 8725). A signed bearer token is still stealable — DPoP (RFC 9449) binds it to a key the client holds, and the OAuth Security BCP (RFC 9700, Jan 2025) requires public clients’ refresh tokens to be sender-constrained or rotated.
- OWASP MASVS · MAS profiles · Mobile Top 10
MASVS v2.1.0 (Jan 2024) is the standard: 24 controls in 8 groups saying what a secure app does. MASWE catalogues how it fails (78 weaknesses, v1.0.0 Aug 2026), MASTG says how to test, and a MAS profile (L1 · L2 · R · P) says how much to test. The Mobile Top 10 (2024) is an awareness list of risks, not a checklist.
- Passkeys — WebAuthn / FIDO2 on iOS
A passkey is a WebAuthn discoverable credential: a key pair made per site by an authenticator (iCloud Keychain, a password manager, a security key). The server keeps only the public key; to sign in, the authenticator signs the server’s one-time challenge together with a hash of the RP ID and the origin the OS/browser vouches for. A look-alike site gets a different RP ID, so there is nothing to phish, replay or leak from a breach.
- Privacy compliance for app developers — GDPR, store rules, kids
The law (GDPR) says: every purpose needs a lawful basis, collect the minimum, honour rights (access, erasure, portability) and bind every processor by contract. The stores enforce the visible parts: in-app account deletion (Apple 5.1.1(v), Google Play), Sign in with Apple token revocation, honest privacy labels / Data safety, ATT before tracking, stricter rules for children. Your SDKs’ data is your data.
- Supply-chain security — from a maintainer’s laptop to your app
Your app ships code from hundreds of people you never vetted, and a package manager runs some of it at install time. Attackers go for the weakest link: a maintainer account (phishing, stolen token), a look-alike name, an install script, a public name shadowing a private one. Defence is layered: pin (lockfile + npm ci), delay (release cooldown), don’t execute (no dependency scripts), verify (provenance), inventory (SBOM) and rehearse the response. OWASP Mobile Top 10 (2024) M2.
- Threat modelling a mobile feature — DFD, trust boundaries, STRIDE
Threat modelling is answering four questions while designing: What are we working on? (draw the data flow) · What can go wrong? (STRIDE at every trust boundary) · What are we going to do about it? (mitigate, eliminate, transfer, accept) · Did we do a good enough job? (tests, review). On mobile the first boundary is the device itself: the client is in the attacker’s hands, so the server enforces.
- WebView & JS-bridge security — WKWebView, React Native
A WebView runs someone’s JavaScript inside your app. The bridge (WebKit message handlers, React Native postMessage, Android addJavascriptInterface) hands that JavaScript native powers — and it is reachable by every script in every frame of whatever page is loaded. Treat each message as untrusted input: check the origin and frame, allowlist commands, restrict navigation, pass data to JS as values, never as code.
- Where data leaks on a phone — and what to wipe
Putting the token in the Keychain secures one copy. The OS makes more copies for you: the keyboard learns what is typed, the app switcher photographs the screen, URLCache writes API responses to Cache.db, logs, backups, the pasteboard, notifications, Spotlight and your SDKs keep theirs. MASVS-STORAGE-2 (“prevents leakage”) and PLATFORM-3 (“UI used securely”) are about those copies — and logout must delete every one.
security-build
- App hardening & privacy
The device is the attacker’s: everything in the .ipa is readable and every client check is hookable — so secrets and real decisions live on the server, and the client only proves things (TLS, App Attest). Privacy is the mirror image: you get one system prompt per permission, and must declare what you touch (purpose strings, privacy manifest, nutrition label).
- Code signing & iOS CI/CD
A build runs on a device only if it is signed with a certificate’s private key and carries a provisioning profile that lists that certificate, the App ID, the entitlements and (dev/ad hoc) the device. CI breaks because the runner has none of that — fastlane match + an App Store Connect API key make signing and upload reproducible and non-interactive.
- Code signing internals — what codesign writes into a Mach-O
A signature is a SuperBlob appended to __LINKEDIT and located by LC_CODE_SIGNATURE. Its heart is the CodeDirectory: a SHA-256 hash of every 4 KiB page of the file (code slots) plus hashes of Info.plist, requirements, resources and entitlements (special slots). The hash of the CodeDirectory — the cdhash — is what a CMS signature from your certificate signs, so one signature covers every byte; the kernel re-hashes each page as it is paged in.
- Crashes & symbolication
A crash report says what killed the process (Exception Type + Termination Reason), where (the crashed thread’s backtrace of image + offset), and which build (the UUID of every binary image). Symbolication turns offsets into function + file:line using the dSYM whose UUID matches — no matching dSYM, no names, ever.
- Keychain · Secure Enclave · biometrics
The Keychain is an encrypted database outside your sandbox (securityd); its rows open with class keys that depend on lock state. The Secure Enclave is a separate chip: keys born there never leave — data in, signature out. Biometrics are secure only when they gate a key, never when they return a Bool.
- Linking & launch time
Static code is copied into your binary at link time (no load cost, but one copy per binary); dynamic code stays a separate Mach-O that dyld maps, fixes up and initialises at every launch. Launch = pre-main (dyld + runtime init) + post-main (UIKit + your didFinishLaunching → first frame); aim for first frame in ≤ 400 ms.
- macOS keychains & the security CLI (CI signing)
macOS has two keychains: the legacy file-based ones (login.keychain-db, System.keychain, any file you create) searched in a search list and guarded by per-item ACLs + a partition list, and the iOS-style data protection keychain (one per user, guarded by access groups from entitlements; needed for iCloud Keychain, biometrics, Secure Enclave). codesign finds its identity (certificate + private key) in the file-based search list — so CI must create, unlock and authorise a keychain.
- Modularization & Swift Package Manager
Cut the app into modules (local SPM packages) along seams that change independently; features depend on each other’s interfaces only, dependencies point down, and a thin app target composes the concrete implementations. The payoff is faster incremental builds and compiler-enforced boundaries.
- Notarization & distribution channels
The channel decides who may install and who vouches: App Store, TestFlight, Custom and Unlisted apps go through App Review and are re-signed by Apple; Ad Hoc and Enterprise run on your signature + profile; a Mac app outside the store is signed with Developer ID, uses the hardened runtime and is notarized — an automated malware + signing scan whose ticket Gatekeeper checks at first launch. “Notarization” for iOS (EU, via alternative marketplaces or the web) is a different thing: a baseline App Review.
- Signing failures — symptom → check → fix
Every signing error is a mismatch between four things that must agree — the identity (certificate + private key in a reachable keychain), the profile (App ID, certificates, entitlements, devices, expiry), the signed entitlements and the bundle (every nested binary signed, nothing changed after). First ask when it fails — build, CI only, install, upload, launch — then decode both sides and diff them instead of toggling Xcode settings.
swift
- Actors · reentrancy · isolation — and why not just @MainActor?
An actor is a reference type whose mutable state is guarded by a serial executor: one task at a time runs its isolated code, outsiders await. It is reentrant — at every await inside it other calls may run, so a check made before a suspension can be stale after. @MainActor is one global actor on the main thread: everything there is serialised with the UI.
- AsyncSequence & AsyncStream
An AsyncSequence is a pull-based sequence whose iterator’s next() is async: for try await suspends until the next element or nil (end). AsyncStream turns a push source (delegate, callback, notification) into one: the producer yields into a continuation, values wait in a buffer (default unbounded, no backpressure), one consumer task pulls them, and onTermination tears the source down.
- Closures in depth — capture, escaping, autoclosure, Sendable
A closure is a function + a context holding what it captured, and it is a reference type. By default it captures variables, not values (a captured var moves into a shared heap box); a capture list copies values when the closure is created. Parameters are non-escaping by default — @escaping says the closure may outlive the call, and that is what brings heap contexts, ARC and cycles.
- Codable in depth — containers, polymorphism, strategies, errors
Codable = Encodable & Decodable. The compiler synthesises CodingKeys + init(from:) + encode(to:) from the stored properties; you write them by hand when the JSON’s shape differs from the type’s. A Decoder hands out containers (keyed · unkeyed · single-value) and every failure is a DecodingError whose codingPath says where.
- Enums & pattern matching — sum types + the 8 patterns
An enum value is exactly one of its cases (a sum type / tagged union); raw values are one compile-time constant per case, associated values are per-instance payloads. switch must be exhaustive, patterns bind and filter, and for library enums @frozen vs @unknown default decides who may add a case.
- Equatable · Hashable · Comparable — the contracts
Equatable = value equality (==); Hashable adds hash(into:) under one rule — a == b ⇒ equal hashes (never the converse); Comparable adds a strict total order from only <. Set/Dictionary find a key by hash first, then == — break the contract or mutate a key and elements vanish.
- Error handling — throws, Result, typed throws, async
Swift errors are values (any type conforming to the empty protocol Error) returned on a separate, checked path: a function says throws, every call site says try, and the error travels up until a do/catch handles it. No stack unwinding across unmarked frames, no cost on the success path, no stack trace.
- Initialization — two phases, three delegation rules
An initializer must give every stored property a value before the instance is used. Structs get a free memberwise init; classes split init into designated (initialise own properties, delegate up to super) and convenience (delegate across to self.init), and run two-phase initialization: phase 1 fills memory bottom-up, phase 2 customises top-down.
- Key paths & access control
A key path (\User.name) is a typed, reusable, uninvoked reference to a property — a class instance you apply with x[keyPath: kp]; its class (read-only vs writable) is decided by what you may do with the property. Access control is lexical: six levels, default internal, and nothing may be exposed through something less visible than itself.
- Macros & result builders — compile-time code generation
A macro (Swift 5.9) is a compiler plugin that receives the syntax tree of its use site and returns new syntax, spliced in at compile time — additive only, no runtime cost. A result builder (@resultBuilder, Swift 5.4) rewrites the statements of a closure into nested static build… calls that fold them into one value — the engine behind SwiftUI’s @ViewBuilder.
- Numerics — overflow, conversions, floating point, money
Swift integer arithmetic traps on overflow (in Debug and Release) — wrapping is opt-in with &+ &- &*; every lossy conversion has a named init that says how it loses. Double is binary IEEE 754, so decimal fractions are approximations: compare with a tolerance, and keep money in Decimal (built from strings) or integer minor units.
- Objective-C essentials + Swift ↔ ObjC interop
An ObjC call is a message: [obj sel] becomes objc_msgSend(obj, @selector(sel)), resolved at runtime in the receiver’s class — hence nil messaging, categories, KVO, swizzling. Swift enters that world via @objc (visible to the runtime) and dynamic (dispatched through it), on NSObject-rooted classes.
- Operators, subscripts, literals, callAsFunction, :=~=
Operators are ordinary (usually static) functions with special syntax; a precedence group decides how an unparenthesised expression parses. Subscripts are property-like members called with [ ]. A literal has no type until context picks an ExpressibleBy…Literal type. :=~= is what switch calls per pattern.
- Optionals — an enum, not a null pointer
T? is sugar for the stdlib enum Optional<Wrapped> { case none; case some(Wrapped) }; nil is .none via ExpressibleByNilLiteral. Absence is part of the type, so the compiler forces you to unwrap — binding, chaining, ??, map, pattern matching — and ! is an explicit bet that traps on nil.
- Ownership · exclusivity · memory layout
Exclusivity is the rule (no overlapping access where one is a write); ownership (borrowing/consuming/ ~Copyable) is the vocabulary for who owns a value and when it dies; layout (MemoryLayout, existentials, refcount headers) is what all of it costs in bytes and atomic ops.
- Parameter packs & the new syntax (5.9 → 6.4)
A parameter pack (5.9) lets one generic declaration take any number of type parameters: <each T> declares the pack, repeat pattern expands the pattern once per element, and each x names the current element — no more 1…10 overloads. Around it, every release since added small syntax that deletes boilerplate: expression if/switch, trailing commas, raw identifiers, weak let, module selectors, some P?, @diagnose, await in defer.
- Property wrappers — what the compiler writes for you
@propertyWrapper (SE-0258, Swift 5.1) is a type with a wrappedValue; annotating @W var x makes the compiler store a hidden _x: W and turn x into a computed property forwarding to _x.wrappedValue — plus $x for projectedValue. SwiftUI’s @State, @Binding, @AppStorage and Combine’s @Published are just such types.
- Strings & collections — Unicode, storage, complexity
A Swift String is a UTF-8 buffer (since Swift 5) seen as a bidirectional collection of Characters, where a Character is an extended grapheme cluster — one user-perceived character of variable byte width. Hence no s[3], count is O(n), and slices (Substring, ArraySlice) share and pin their parent’s storage. All stdlib collections are value types with copy-on-write.
- Swift ↔ C / C++ interop
Swift reads C headers through its built-in Clang importer: a header exposed as a module (module map; or a bridging header in an app target) becomes global Swift functions and types — C scalars map to CInt/CChar…, pointers to Unsafe*Pointer. C++ (Swift 5.9+, opt-in) imports copyable classes as value types. The other way, @c (Swift 6.3; before it the unofficial @_cdecl) exports a Swift function under a C symbol.
- Swift 6 · strict concurrency & data-race safety
In the Swift 6 language mode data-race safety is a compile-time guarantee: all mutable state belongs to one isolation domain (an actor, a global actor like @MainActor, or nonisolated); a value crosses domains only if it is Sendable or provably never used again by the sender (region isolation / sending). Swift 5 warnings become errors.
- Swift attributes & compiler directives — a catalogue
An attribute (@name(args)) changes how the compiler treats a declaration or type — what it exports, how it dispatches, what it checks — without changing its code; a directive (#if, #warning, #fileID…) acts at compile time on the source itself. The ones that matter most are about boundaries: module/ABI (@inlinable, @frozen), language (@objc), concurrency (@preconcurrency) and build configuration (#if).
- Swift compiler pipeline + runtime internals
The frontend parses, type-checks (a constraint solver), lowers to SIL — Swift’s own IR that still sees generics, ownership and ARC — runs mandatory then performance passes, then emits LLVM IR. At run time every type has metadata; generic and protocol code goes through value/protocol witness tables unless the optimiser could specialise it, which needs the body visible.
- Swift Regex — literal, runtime, RegexBuilder
Regex<Output> (Swift 5.7, iOS 16): Output is the typed shape of a match, (Substring, captures…). Three builds: literal (checked + typed at compile time), Regex(string) (runtime, throws, AnyRegexOutput), RegexBuilder (typed, composable, embeds Foundation parsers). Matches Characters, returns String.Index ranges.
- Swift syntax tricks — closures, calls & what they desugar to
Almost every “clever” call in Swift is sugar the type checker rewrites into an ordinary call: a trailing closure is the last argument, \.name becomes a closure, c(x) becomes c.callAsFunction(x), box.name becomes box[dynamicMember:], :=?? receives its right side unevaluated, and #line in a default argument is read at the caller. Say the rewrite and you have explained it.
- Swift syntax tricks — control flow, scopes & errors
Every { } is a scope, and every way out of it — end, return, break, continue, throw — runs that scope’s defers last-in first-out, innermost scope first. A label names a loop/if/do/switch so one break/continue leaves several scopes at once; guard binds into the enclosing scope and must leave it; patterns (case let x?, where) turn loops and conditions into filters.
- Swift syntax tricks — generics, protocols & some/any
A generic signature is a set of requirements the compiler checks at the call site: some P in a parameter is an unnamed generic <T: P>, any P is a box for any conformer, a primary associated type (Collection<Int>) constrains either, and where adds same-type / superclass / conformance rules. Which method body runs is decided by one question: is it a protocol requirement? Yes → dynamic (witness table); no → the static type picks.
- Time in Swift — Clock, Duration, timers
Clock (Swift 5.7, iOS 16) abstracts a time source: now, minimumResolution, sleep(until:tolerance:). ContinuousClock keeps counting while the system sleeps, SuspendingClock stops; both are monotonic, unlike Date, which is wall-clock and can jump. Measure elapsed time with a clock, store absolute moments as Date, and inject the clock so tests never really wait.
- Unsafe pointers · Unmanaged · metatypes · Mirror · casts
Unsafe = you, not the compiler, own lifetime, initialisation, alignment, type binding and bounds. Reflection is deliberately thin: metatypes are values (T.Type), Mirror only reads stored properties, casts query runtime metadata.
swiftui
- Animations — SwiftUI & UIKit
You never animate frame by frame: you change state (SwiftUI) or set the final value (UIKit) inside an animation context, and the framework interpolates every animatable property old → new. The questions are always: which change is in the context, and can it be interpolated?
- Async work & data flow in SwiftUI views
SwiftUI owns the lifetime of async work: .task starts with the view and is cancelled when the view goes away or its id changes. Views are @MainActor: writing state after await is safe, blocking the main actor is your bug. Truth lives in @State / @Observable; effects hang off .task(id:), onChange, .refreshable.
- Custom modifiers, styles & containers
A modifier wraps the view in a generic type (ModifiedContent<Content, M>) — static structure, so the wrap keeps identity. Reuse has three shapes: a ViewModifier (a look that may own state), a style (a control’s look without losing its behaviour, inherited through the environment) and, since iOS 18, a custom container that lays out the resolved subviews of its content.
- Lists, lazy stacks & scrolling
VStack builds every child now; LazyVStack builds a row only as it nears the viewport (no reuse); List reuses platform cells but collects all ids up front. ForEach ids decide which state, animation and callbacks belong to which datum — and since iOS 17/18 the scroll view reports position, snapping, geometry and visibility declaratively.
- Rendering pipeline — layers, frames, hitches
Your app never draws the screen: it edits a layer tree and commits it once per frame to the out-of-process render server, which renders it on the GPU for the next vsync. Every frame has a deadline — 16.67 ms at 60 Hz, 8.33 ms at 120 Hz (ProMotion). Miss it in your process → commit hitch; miss it in the render server → render hitch. Either way the old frame stays on screen.
- Swift Charts — marks, scales, axes, selection
Swift Charts (iOS 16) is a declarative grammar of graphics: a Chart is a list of marks (one visual element per data item); each mark maps data to visual properties through .value("Label", v) plottable values; scales turn the data domain into pixels and colours, and axes, legend, VoiceOver and Audio Graphs are derived from the same labels — for free.
- SwiftUI ↔ UIKit interop
A representable struct wraps a long-lived UIKit object: make runs once per identity, update on every change, a Coordinator carries callbacks back. The other way, UIHostingController is a real view controller showing a SwiftUI view.
- SwiftUI accessibility & Dynamic Type
SwiftUI derives an accessibility tree from the view tree: every Text, Image and control becomes an element, stacks are transparent. Your job is to shape that tree — one stop per idea (group, label, value, actions) — and let text grow (Dynamic Type) while the layout reflows and motion respects user settings.
- SwiftUI App, scenes & lifecycle
A SwiftUI app is a value: @main struct MyApp: App whose body returns scenes. A scene is a template the system instantiates into one or more windows (UIWindowScenes), each with its own view tree, @State, @SceneStorage and scenePhase. UIKit’s delegates come back through an adaptor; URLs, activities and background wake-ups are delivered to scenes by modifiers.
- SwiftUI Environment & Preferences
Two implicit channels through the view tree: the environment flows down (an ancestor sets a value, every descendant can read it), preferences flow up (descendants emit values, SwiftUI reduces them, an ancestor reads the result). Explicit init parameters remain the default for a view’s own data.
- SwiftUI Gestures & Canvas drawing
Gestures are value types composed with combinators (replacing recognizer-delegate arbitration); @GestureState resets on end and cancel. Shape = one vector view, Canvas = one immediate-mode view for thousands of primitives, drawingGroup() = flatten a subtree into one offscreen image before display.
- SwiftUI layout system
Layout is a negotiation, not a constraint solver: the parent proposes a size, the child chooses its own size (it may ignore the offer), the parent places the child. Every modifier is a new parent in that chain — so order matters.
- SwiftUI navigation
Since iOS 16 navigation is data: a NavigationStack renders a path (an array of Hashable values) that you own; navigationDestination(for:) maps each value type to a screen. Push = append, pop = remove, deep link = assign a whole path.
- SwiftUI performance & identity
SwiftUI keeps state and view lifetime per identity, and re-runs body only for views whose dependencies changed. Fast SwiftUI = stable identity (state survives, diff is cheap) + narrow dependencies (few bodies run) + cheap bodies (each run is fast).
- TipKit — rules, pacing, invalidation
A tip is a small, transient view that teaches one non-obvious feature. You declare content + eligibility on a Tip; TipKit (iOS 17) keeps state in a persistent datastore, evaluates rules (@Parameter values, counted Tips.Event donations), spaces tips by a global display frequency, and retires a tip for good once invalidated — user acted, closed it, or it hit its cap.
- Transferable, drag & drop, sharing, pickers
Transferable (iOS 16) describes once, as an ordered list of representations keyed by UTType, how a value leaves and enters the app; ShareLink, .draggable, .dropDestination, PasteButton and PhotosPicker all consume it — replacing separate UIActivityItemSource, NSItemProvider and UIPasteboard code.
testing
- Async & network testing — expectations, confirmations, MockURLProtocol, clocks
Wait for the event, never for time. async code: an async throws test that awaits. Callbacks: XCTestExpectation + await fulfillment(of:), or Swift Testing’s confirmation (which does not wait) or a continuation. Network: the real URLSession over a stub URLProtocol. Time: inject a Clock or scheduler and advance it.
- Flaky tests · CI · coverage · TDD
A flaky test passes and fails on the same code. The cause is nondeterminism — async waits, races, test order, network, time — so remove the source; a retry only measures it. Coverage says what ran, not what was checked. TDD = test list → one failing test → pass → refactor, minutes per loop.
- Test doubles — Dummy · Stub · Spy · Mock · Fake
A test double (Gerard Meszaros, xUnit Test Patterns, 2007; Fowler: “think stunt double”) replaces a DOC (depended-on component) so the SUT can be tested alone. The five differ in what they do with the SUT’s indirect inputs (what the DOC returns or throws) and indirect outputs (the calls the SUT makes): a Stub feeds inputs, a Spy records outputs for the test to check, a Mock checks outputs itself, a Fake is a lighter working implementation, a Dummy is never called.
- Testable design — DI, seams & legacy code
A seam is “a place where you can alter behavior in your program without editing in that place”; every seam has an enabling point, “a place where you can make the decision to use one behavior or another” (Michael Feathers, Working Effectively with Legacy Code, 2004). In Swift the seam is a protocol or closure the type receives, and the enabling point is its init. Code that reaches for .shared, Date() or UserDefaults.standard has none.
- Testing fundamentals — the pyramid, FIRST, AAA
Catch each bug at the lowest level that can: many small, fast, deterministic tests and few broad ones (the pyramid). Test behaviour through the public API, so a test fails only when behaviour changes. A good test is FIRST and reads Arrange → Act → Assert.
- Testing ViewModels, Coordinators, UI & snapshots
Logic lives in a ViewModel and a router with injected dependencies, tested in-process in milliseconds; snapshots pin what a view looks like (one simulator, one reference file); UI tests drive the real app from another process through the accessibility tree — few, slow, addressed by identifier.
- XCTest & Swift Testing — lifecycle, macros, traits, what changed
XCTest: subclass XCTestCase, name methods test…, assert with XCTAssert*; a fresh instance per test method. Swift Testing (open source, in the Swift toolchain, all Swift platforms): @Test functions, any type is a suite, two macros #expect / #require, traits and arguments — run in parallel, in one process by default. Both live in one target; UI automation, XCTMetric performance tests and Objective-C stay in XCTest.
typescript
- TypeScript generics & type-level programming
Type parameters are solved by inference at each call and bounded by extends. Conditional, mapped and template-literal types add a small pure functional language — if, pattern-bind, map over keys, recurse — that the checker runs at compile time and erases from the JavaScript, inside fixed depth and union-size limits.
- TypeScript in practice — tsconfig, modules, 6.0 & 7.0, boundaries
Types are erased: tsc proves consistency inside the program, nothing checks the data that enters it. The config decides how strict the proof is, how imports resolve for whoever loads the output, and which syntax a per-file transpiler or Node can strip. Since July 2026 tsc is the native Go port (TypeScript 7); 6.0 was the last JavaScript-based release.
- TypeScript type system — how the checker reasons
A type is a set of values; assignability is subset, judged by shape, not by name. A union must be narrowed along control flow before use. Types are erased; enums, namespaces with code and parameter properties are TypeScript syntax that emits JavaScript. Soundness is traded away on purpose in known places: any, as, method parameters, readonly aliasing.