skip to content

Swift

Swift is the language of Apple's platforms and a growing server and embedded language: value types, optionals, protocols, ARC and checked concurrency. iOS loops test it apart from the UI.

on this pageshow

explore

questions

271 · 15 sections

In Swift, what is the difference between let and var, and why do Swift teams declare with let by default?

level: juniorimportance: must knowfreq 82%
basics
~20 s

let binds a name to a value exactly once and the compiler rejects any later assignment; var allows reassignment. Teams default to let because it states intent and the compiler warns when a local var is never mutated.

open as a page

In Swift, how does type inference choose a type for a literal, and when must you write a type annotation instead?

level: juniorimportance: must knowfreq 68%
basics
~20 s

A Swift literal has no type of its own: the compiler takes one from context, such as an annotation or the other operands, else defaults to Int, Double, String or Bool. Annotate when that default is wrong or nothing can be inferred.

open as a page

In Swift, how does a guard statement differ from an if statement, and why must guard's else branch exit the enclosing scope?

level: juniorimportance: must knowfreq 78%
basics
~20 s

A guard runs its else branch when its condition fails, and that branch must leave the enclosing scope through return, break, continue, throw or a call that never returns. Values the condition binds stay usable for the rest of the scope.

open as a page

In Swift, how do the closed range `a...b`, the half-open range `a..<b` and one-sided ranges like `items[2...]` differ, and when does a range trap?

level: juniorimportance: must knowfreq 70%
basics
~20 s

a...b is a ClosedRange including b; a..<b is a Range stopping before b, so a..<a is empty. One-sided forms like items[2...] take the missing bound from the collection. Inverted bounds trap, as does slicing past an array's indices.

open as a page

In Swift, when does a defer block run, and in what order do several defer blocks in the same scope execute?

level: middleimportance: must knowfreq 60%
basics
~20 s

A defer block runs when control leaves the scope it was declared in, by return, break, continue, a thrown error or reaching the closing brace. Several defer blocks in one scope run in reverse order: the last one written runs first.

open as a page

In Swift, how do you unwrap an Optional with if let and guard let, and when is each the better fit?

level: juniorimportance: must knowfreq 85%
basics
~20 s

if let binds the wrapped value only inside its own braces; guard let binds it for the rest of the enclosing scope and its else branch must exit. Since Swift 5.7, if let name unwraps an existing variable of the same name.

open as a page

In Swift, what type does an optional chain like profile.manager?.avatarURL return, and how does ?? supply a fallback?

level: middleimportance: must knowfreq 75%
basics
~20 s

An optional chain always returns one level of optional: if any link is nil, the rest of the expression is skipped and the chain is nil. The ?? operator unwraps that result or evaluates its right-hand default, only when needed.

open as a page

In Swift, why does `quantity * unitPrice` fail to compile when quantity is an Int and unitPrice a Double, while `3 * 19.99` compiles?

level: middleimportance: must knowfreq 70%
basics
~20 s

Swift never converts one numeric type to another implicitly, so Int * Double has no matching operator. Literals stay untyped until context picks a type, so 3 becomes a Double in 3 * 19.99. Convert variables explicitly: Double(quantity) * unitPrice.

open as a page

In Swift, why can a String's count, utf8.count and unicodeScalars.count return three different numbers for the same username?

level: middleimportance: must knowfreq 65%
basics
~10 s

String.count counts Characters, and each Character is an extended grapheme cluster that may hold several Unicode scalars; unicodeScalars.count counts those scalars and utf8.count counts encoded bytes, so emoji or accents make all three differ.

open as a page

In Swift, why can't you subscript a String with an Int, and what does index(_:offsetBy:) cost when you truncate a message preview?

level: seniorimportance: must knowfreq 60%
basics
~20 s

Characters in a Swift String have variable width, so reaching the nth one means walking from an end. Swift marks the Int subscript unavailable instead of hiding that cost, and index(_:offsetBy:) is O(n) in the distance it moves.

open as a page

In Swift, how do you choose between Array, Set and Dictionary, and what does a membership or key lookup cost in each?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Use Array for ordered values that may repeat, Set for unique values you test for membership, and Dictionary to find a value by key. Array.contains(:) is a linear scan; Set.contains(:) is O(1); a Dictionary key lookup returns an optional.

open as a page

In Swift, what does declaring Codable on a struct give you, and what must its stored properties satisfy to decode a flat JSON object?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Codable (Encodable & Decodable) makes the compiler generate a CodingKeys enum, init(from:) and encode(to:) when every stored property's type conforms. Non-optional keys must be present; an Optional property decodes as nil when its key is missing or null.

open as a page

In Swift, when does the compiler synthesize Equatable and Hashable for your own type, and when must you write them yourself?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Swift synthesizes == and hash(into:) when you declare Equatable or Hashable in the type's own file and every stored property (struct) or associated value (enum) conforms. Classes never get it; enums without payloads conform even undeclared.

open as a page

In Swift, what is the difference between map, compactMap and flatMap when you transform a sequence of values?

level: juniorimportance: must knowfreq 75%
basics
~10 s

Swift's map returns exactly one result per element; compactMap keeps only the non-nil results of a closure that returns an optional; flatMap concatenates the sequences its closure returns into one flat array.

open as a page

Swift's Array, Set and Dictionary are value types, so when does assigning or passing one actually copy its elements?

level: middleimportance: must knowfreq 72%
basics
~20 s

Assigning, passing or returning a standard collection copies only a reference to its shared storage. The elements are copied when a mutation hits storage that another copy still shares; a uniquely owned buffer is mutated in place.

open as a page

In Swift, how can a closure expression passed to a function be shortened, and how do trailing and multiple trailing closures change the call site?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Swift infers a closure's parameter and return types from the call, so a single-expression closure can drop its types, return and parameter names ($0, $1). A final closure argument can move after the parentheses as a trailing closure.

open as a page

In Swift, how do you store validation functions such as isNotEmpty in a dictionary of rules, and what type does each entry have?

level: juniorimportance: must knowfreq 60%
basics
~20 s

A Swift function is a value with a function type such as (String) -> Bool. Naming it without parentheses, isNotEmpty rather than isNotEmpty(), yields the function itself, so it can sit in a [String: (String) -> Bool] dictionary, be passed or be returned.

open as a page

In Swift, what is the difference between a parameter's argument label and its parameter name, and what does writing _ change at the call site?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A Swift argument label is the word callers write before an argument; the parameter name is what the function body uses. The label defaults to the name, a separate word overrides it, and _ removes it.

open as a page

In Swift, why must an image downloader's completion-handler parameter be marked @escaping, and why are closure parameters non-escaping by default?

level: middleimportance: must knowfreq 72%
basics
~20 s

A closure escapes when it is stored or called after the function returns, as a completion handler is, so Swift requires @escaping on that parameter. Non-escaping is the default because the compiler can then guarantee the closure's lifetime ends with the call.

open as a page

In Swift, what do [weak self] and [unowned self] do in a download's completion handler when the screen closes before it finishes?

level: middleimportance: must knowfreq 82%
basics
~20 s

[weak self] captures an optional reference that becomes nil once the screen is deallocated, so the handler unwraps it and returns early. [unowned self] captures a non-optional reference assumed to be alive; reading it after deallocation traps.

open as a page

In Swift, what is the difference between an enum's raw values and its associated values, and can one enum declare both?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Raw values are per-case constants of one shared type, fixed in the declaration; associated values are payloads supplied each time a value is created, typed per case. A Swift enum with a raw type cannot give any case associated values.

open as a page

In Swift, how does a switch match tuple and range patterns, such as a deep link's (host, path) pair or an HTTP status code?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A Swift switch matches a tuple element by element, with _ ignoring a position, and a range by containment. The first matching case in source order wins; a switch over Int or String still needs a default case.

open as a page

In Swift, what does a String-backed enum's `init?(rawValue:)` return for a value the API never documented, and how are implicit raw values chosen?

level: middleimportance: must knowfreq 62%
basics
~10 s

init?(rawValue:) returns nil when no case has that exact, case-sensitive raw value. Implicit raw values are the case name for String and the previous value plus one, from 0, for integer raw types.

open as a page

In Swift, how do you bind an enum case's associated values in a switch, and when do you use if case, guard case or for case instead?

level: middleimportance: must knowfreq 75%
basics
~20 s

Bind payload values with let or var inside the case pattern, as in case .failure(let status, _), optionally filtered by where. Use if case or guard case to test one case without a switch, and for case to loop over matches.

open as a page

When does Swift synthesize `CaseIterable` for an enum, and what do you do for an enum whose cases carry associated values?

level: middleimportance: should knowfreq 45%
basics
~20 s

Swift synthesizes allCases when an enum declares CaseIterable, has no associated values and no @available attributes on its cases, and the conformance is in the enum's own file. Otherwise you write static var allCases yourself.

open as a page

In Swift, how does a subclass replace an inherited method with `override`, and how does it reach the superclass version through `super`?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A Swift subclass marks a replacement method, property or subscript with override. The compiler rejects a missing override and also an override that matches nothing. Inside it, super.method() calls the superclass implementation, which Swift never forces you to call.

open as a page

In Swift, why must a struct method that changes a stored property be marked `mutating`, and why can't you call it on a `let` constant?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A struct or enum method sees self as immutable unless it is marked mutating, which grants write access to the value for the call. A let constant never grants that access, so a mutating call on one does not compile.

open as a page

In Swift, what is the difference between a stored property and a computed property, and how is a read-only computed property declared?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A stored property holds a value in each instance's memory; a computed property stores nothing and runs its getter, and optional setter, on every access. A read-only computed property has only a getter and is still declared with var.

open as a page

In Swift, if a shopping cart passed to two screens is a struct rather than a class, what happens when one screen adds an item?

level: juniorimportance: must knowfreq 85%
basics
~20 s

A struct is copied whenever it is assigned or passed, so each screen holds its own cart and the other screen never sees the new item. A class instance is shared, so both screens see it.

open as a page

In Swift classes, how do designated and convenience initializers differ, and which delegation rules does the compiler enforce between them?

level: middleimportance: must knowfreq 55%
basics
~20 s

A designated initializer fully initializes the properties its class introduces and, in a subclass, calls a designated initializer of the immediate superclass. A convenience initializer, marked convenience, must call another initializer of the same class with self.init, ultimately reaching a designated one.

open as a page

What can a Swift extension add to an existing type, what can it not add, and why declare a protocol conformance in one?

level: juniorimportance: must knowfreq 68%
basics
~20 s

An extension adds computed properties, methods, initializers, subscripts, nested types and protocol conformances. It cannot add stored instance properties, property observers, deinitializers or, on a class, designated initializers. Declaring a conformance in an extension groups that protocol's members.

open as a page

In a Swift protocol, what separates a `{ get }` property requirement from a `{ get set }` one, and which conformer properties satisfy each?

level: juniorimportance: must knowfreq 62%
basics
~20 s

A { get } requirement accepts any property of that name and type: a let, a var or a read-only computed property. A { get set } requirement needs something settable: a stored var or a computed property with a setter.

open as a page

In Swift, how does a type conforming to a protocol with an `associatedtype` choose the concrete type, and when must it write a typealias?

level: middleimportance: must knowfreq 60%
basics
~20 s

An associatedtype is a placeholder each conformer fills. Swift usually infers it from the witnesses, such as save(_ entity: User); write typealias Entity = User when no requirement mentions it, when inference is ambiguous, or to make the choice explicit.

open as a page

In Swift, how does a protocol extension supply a default implementation for a requirement, and when does a conforming type's own version replace it?

level: middleimportance: must knowfreq 75%
basics
~20 s

A protocol extension can implement a method or computed-property requirement, and conformers that declare nothing get it. A conformer declaring a member with the same name, argument labels and types replaces that default everywhere, including calls through the protocol.

open as a page

Why does Swift reject `weak var delegate: CacheDelegate?` until the `CacheDelegate` protocol inherits from `AnyObject`?

level: middleimportance: must knowfreq 72%
basics
~20 s

A weak reference only makes sense for class instances, and a plain protocol can be adopted by structs and enums. Adding AnyObject to the protocol's inheritance list makes it class-only, so the compiler knows every conformer is a reference and accepts weak.

open as a page

In Swift, what do the is, as?, as! and as operators each do, and which one fits a downcast that might fail?

level: juniorimportance: must knowfreq 75%
basics
~20 s

is returns a Bool; as? returns an optional, nil on failure; as! returns the value or traps; plain as only does conversions the compiler proves, such as upcasts and bridging. A downcast that might fail takes as?.

open as a page

In Swift, how does a generic function like `largest(in:)` infer `T` at the call site, and why must it constrain `T` to `Comparable`?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Swift fixes T at each call from the argument types, so [Int] makes T Int. The body may use only what the constraints promise, so value > best compiles only after T: Comparable is declared.

open as a page

In Swift, when does an as! forced cast trap at run time, and when is it acceptable instead of as? in production code?

level: middleimportance: must knowfreq 62%
basics
~20 s

as! traps whenever the cast fails, including when the input is nil. It is acceptable only where failure would be a programmer error the same code rules out, such as a type it registered itself; data from outside takes as?.

open as a page

In Swift, what is the difference between `some PaymentProvider` and `any PaymentProvider` as a parameter type and as a return type?

level: middleimportance: must knowfreq 78%
basics
~20 s

some PaymentProvider stands for one concrete conforming type the compiler tracks: the caller picks it for a parameter, the function picks it for a return. any PaymentProvider is a box whose concrete type can differ from value to value.

open as a page

In Swift, what values can Any and AnyObject each hold, and what happens when a struct is stored as AnyObject?

level: middleimportance: should knowfreq 50%
basics
~20 s

Any holds a value of any type, including structs, closures, metatypes and optionals. AnyObject holds class instances, so a struct needs an explicit as AnyObject, which bridges it or wraps it in a new box object.

open as a page

In Swift, what does `Result<Success, Failure>` hold, and how does a caller read it with `switch` or `Result.get()`?

level: juniorimportance: must knowfreq 68%
basics
~10 s

Result is a standard-library enum with two cases, success(Success) and failure(Failure), where Failure must conform to Error. Callers switch over both cases or call get(), which returns the value or throws the stored error.

open as a page

In Swift, how do you define an error type, mark a function as throwing, and handle its errors with do-catch?

level: juniorimportance: must knowfreq 82%
basics
~20 s

Conform a type, usually an enum, to Error, write throws before the return arrow, and mark each throwing call with try. Inside do, an error jumps to the first matching catch; a pattern-less catch binds it as error.

open as a page

In Swift, what do `assert`, `precondition` and `fatalError` each do in `-Onone`, `-O` and `-Ounchecked` builds?

level: middleimportance: must knowfreq 62%
basics
~20 s

assert checks only in -Onone (Debug) builds; precondition checks in -Onone and -O, so it traps in Release too; fatalError stops the program in every build. In -Ounchecked, assert and precondition are not evaluated and the optimizer may assume they hold.

open as a page

In a Swift do-catch, which catch clause runs for a thrown error, and how do case, as, is and where patterns match?

level: middleimportance: must knowfreq 62%
basics
~20 s

Swift tests catch clauses in source order and runs the first whose pattern matches: a case pattern can bind associated values, let x as T casts, is T tests the type, and where adds a condition. Unmatched errors propagate.

open as a page

In Swift, what do try? and try! do with a thrown error, and when does try? hide a bug?

level: middleimportance: must knowfreq 72%
basics
~20 s

try? turns a thrown error into nil and discards it, so the result is optional; try! traps at run time, even in -O builds. try? hides a bug when the failure needed logging, showing, or telling apart from a real nil.

open as a page

In Swift, which references keep a class instance alive under ARC, and at what moment does its deinit run?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Every strong reference keeps a Swift class instance alive: variables, constants, stored properties (a struct's included), collection elements and closure captures. When the last one is released, ARC runs deinit synchronously at that point and then frees the memory.

open as a page

In Swift, why do a screen and the view model it owns never deinit when the view model's delegate holds the screen strongly?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Each object keeps the other's strong reference count above zero, so ARC never deallocates either and neither deinit runs. Declaring the view model's delegate as weak var breaks the cycle: the screen is freed first, then the view model it owned.

open as a page

How does Swift's ARC differ from a tracing garbage collector, and what does that buy and cost a Swift app?

level: middleimportance: must knowfreq 60%
basics
~20 s

Swift's ARC compiles retains and releases into the code and frees an instance the moment its last strong reference goes. That buys deterministic deinit and no collector pauses; it costs counting work on every reference copy and leaves reference cycles uncollected.

open as a page

In Swift, when do you declare a back-reference `unowned` instead of `weak`, and what happens if it is read after its object is gone?

level: middleimportance: must knowfreq 72%
basics
~20 s

Use unowned when the referenced object always lives at least as long as the holder, so it never needs to be nil. Reading an unowned reference after its object is destroyed traps; unowned(unsafe) drops that check and reads freed memory.

open as a page

What does Swift's law of exclusivity forbid, and when do two accesses to the same variable conflict?

level: juniorimportance: should knowfreq 30%
basics
~20 s

Swift forbids modifying a variable while another access to it is in progress: two accesses conflict when they hit the same location, are not both reads (or both atomic) and overlap in time. Violations are compile errors or run-time traps.

open as a page

In Swift, what does marking a view model class `@MainActor` guarantee, and how does background work hand its results back to it?

level: juniorimportance: must knowfreq 80%
basics
~20 s

@MainActor isolates every property and method of the class to the main actor, so the compiler lets only main-actor code touch them synchronously. Background code reaches the view model with await: an isolated method, MainActor.run, or a @MainActor closure.

open as a page

In Swift, what does `await` mark inside an async function, and what happens to the thread when the function suspends there?

level: juniorimportance: must knowfreq 75%
basics
~20 s

await marks a possible suspension point. If the call does suspend, the async function gives up its thread instead of blocking it, other work runs there, and the function later resumes, perhaps on another thread, where shared state may have changed.

open as a page

With GCD, how do serial and concurrent DispatchQueues differ, and why must a star-chart screen's UI update go back to DispatchQueue.main?

level: juniorimportance: must knowfreq 82%
basics
~20 s

A serial DispatchQueue runs one work item at a time, in order; a concurrent queue starts items in order but can run several at once. DispatchQueue.main is a serial queue tied to the main thread, where all UIKit and SwiftUI updates belong.

open as a page

In Swift, how does a for await loop over an AsyncSequence work, when does it need try, and what ends it?

level: juniorimportance: must knowfreq 55%
basics
~20 s

A for await loop awaits its iterator's next() before every pass, suspending until the next value or the end. It needs for try await when the sequence can throw, and ends when next() returns nil or throws, or the body breaks.

open as a page

In Swift, how does `Task { }` start async work from a synchronous button action, and what does the returned handle let you do?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Task { } creates an unstructured task that starts at once and returns a Task<Success, Failure> handle. Keep the handle to await value or result or to call cancel(); dropping it neither cancels the task nor surfaces its errors.

open as a page

In Swift, how does contacts.map(\.name) work, and why does passing a stored KeyPath variable to map fail?

level: juniorimportance: must knowfreq 60%
basics
~20 s

A key-path literal such as .name converts to a (Contact) -> String function wherever one is expected, so map applies it to each element. Only the literal converts; a stored KeyPath value needs a closure: { $0[keyPath: path] }.

open as a page

In Swift, what must a @propertyWrapper type declare, and what does the compiler generate when you write @Trimmed var email: String?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A @propertyWrapper type must declare a non-static wrappedValue property. For @Trimmed var email, Swift synthesizes private storage _email of type Trimmed and turns email into a computed property that forwards get and set to _email.wrappedValue.

open as a page

In a Swift property wrapper, what is projectedValue, and how do $volume and _volume differ from volume?

level: middleimportance: must knowfreq 62%
basics
~10 s

projectedValue is an optional property a wrapper declares to expose extra information; Swift surfaces it as $volume with volume's access level. volume forwards to wrappedValue, and _volume is the private wrapper instance itself.

open as a page

In Swift, what does the @resultBuilder attribute do, and how does a closure of separate expression lines become one value?

level: juniorimportance: should knowfreq 35%
basics
~20 s

@resultBuilder marks a type whose static build methods the compiler calls. Where that type is written as an attribute, the compiler rewrites the body: each expression line becomes a partial result, and buildBlock (or buildPartialBlock) combines them into the return value.

open as a page

In Swift, what happens at compile time when code calls a freestanding macro such as `#checkedURL("https://example.com")`, and how does that differ from a function call?

level: juniorimportance: should knowfreq 40%
basics
~20 s

The compiler expands it during the build: the macro's implementation receives the call's syntax and returns code that replaces the call, which is then type-checked. A function runs later with real values; a macro's thrown error fails the build.

open as a page

In Swift, what access level does a declaration get when you write no modifier, and how do `private` and `fileprivate` differ, including in extensions?

level: juniorimportance: must knowfreq 75%
basics
~20 s

With no modifier a Swift declaration is internal: usable in every file of its module, invisible outside it. private limits use to the enclosing declaration and its same-file extensions; fileprivate opens it to the whole source file.

open as a page

In a mixed Swift and Objective-C app, why can't an Objective-C file call a new Swift method, and what makes it visible?

level: middleimportance: must knowfreq 62%
basics
~20 s

Objective-C sees Swift only through the compiler-generated ModuleName-Swift.h header, which prints only declarations exposed with @objc. Since Swift 4, sitting in an NSObject subclass no longer exposes a method by itself, so a new method needs @objc and Objective-C-representable types.

open as a page

When Swift imports an Objective-C header, how do nullability annotations, lightweight generics and NS_ENUM declarations decide the Swift types you get?

level: middleimportance: must knowfreq 58%
basics
~20 s

Unannotated Objective-C pointers import as implicitly unwrapped optionals, nullable as optionals, nonnull as plain types; NSArray<NSString *> becomes [String] while a bare NSArray becomes [Any]; NS_ENUM becomes a non-frozen Swift enum and NS_OPTIONS an OptionSet struct.

open as a page

In Swift, what is the difference between `open` and `public` on a class and its methods for code in another module?

level: middleimportance: must knowfreq 70%
basics
~20 s

Both make a class and its members usable from other modules. Only open also lets another module subclass the class or override the member; a public class can be subclassed, and its public methods overridden, only inside its defining module.

open as a page

In Swift, how do `private(set)` and `internal(set)` restrict a property's setter, and what can code outside that scope still do with it?

level: middleimportance: must knowfreq 65%
basics
~20 s

A setter modifier gives a property's setter a lower access level than its getter. Outside that scope code can read the property, but cannot assign it, pass it inout or call a mutating member on it.

open as a page

In Swift, how does marking a class or a method `final` change the way calls to it are dispatched, and why can that run faster?

level: juniorimportance: must knowfreq 55%
basics
~20 s

A non-final class method is called through the class's vtable, an indirect call the compiler cannot see through. Final promises that no override exists, so the compiler calls the one implementation directly and can inline it.

open as a page

In Swift, which dispatch mechanism handles a call to a struct method, an overridable class method, a protocol requirement and an `@objc dynamic` method?

level: middleimportance: must knowfreq 65%
basics
~20 s

Swift picks per call site: struct, enum and final methods are direct calls; overridable class methods use the class vtable; protocol requirements called on a generic or existential value use a witness table; @objc dynamic members use objc_msgSend.

open as a page

In Swift, which values need a heap allocation instead of the stack, and when can the optimizer keep a class instance on the stack?

level: middleimportance: must knowfreq 65%
basics
~20 s

Class instances, escaping-closure contexts and the vars they capture, indirect enum payloads, collection buffers and oversized existentials are heap-allocated; a struct is stored inline wherever it lives. Under -O, a class instance that never escapes can be stack-promoted.

open as a page

In Swift, what do the -Onone, -O, -Osize and -Ounchecked optimization levels change, and why do you time code only in an optimized build?

level: juniorimportance: should knowfreq 45%
basics
~10 s

-Onone barely optimizes so debugging works; -O optimizes for speed, -Osize for smaller code, and -Ounchecked also drops precondition and overflow checks. Debug timings mislead, so profile an -O or -Osize build.

open as a page

In Swift, how is a method declared in a class extension dispatched, and why can't a subclass override it unless it is `@objc`?

level: middleimportance: should knowfreq 30%
basics
~20 s

A method declared in a class extension gets no vtable slot, so Swift calls it directly, as if final, and rejects an override. Marked @objc on Apple platforms, it is dispatched by Objective-C message instead, which an override can replace.

open as a page

In Swift, how do #available, #unavailable and @available let an app call an API newer than its deployment target?

level: middleimportance: must knowfreq 65%
basics
~20 s

@available records the OS versions a declaration needs; calling it from code that may run on an older OS fails to compile unless the call sits inside an #available check, which tests the OS at run time. #unavailable is the inverse.

open as a page

In Swift, how does the language mode differ from the compiler version, and what does moving a module to Swift 6 mode change?

level: middleimportance: must knowfreq 60%
basics
~20 s

The compiler version is the toolchain, such as Swift 6.4; the language mode is the dialect it compiles each module in: 4, 4.2, 5 or 6. Swift 6 mode turns on its scheduled source-breaking changes, most visibly data-race errors.

open as a page

What do Swift's design goals of safety, speed and expressiveness mean in practice, with one concrete language rule behind each?

level: juniorimportance: should knowfreq 50%
basics
~20 s

Safe means Swift defines away common bugs: values are initialized before use, nil must be handled through Optional, and overflow or out-of-bounds indexing traps. Fast means optimized native code. Expressive means type inference, closures and pattern matching.

open as a page

In Swift, how do -enable-upcoming-feature and -enable-experimental-feature differ, and which upcoming features does Swift 6 mode already include?

level: middleimportance: should knowfreq 45%
basics
~20 s

-enable-upcoming-feature turns on one accepted, source-breaking change before its language mode makes it default; -enable-experimental-feature is for unfinished work with no stability promise, some of it refused by release compilers. Swift 6 mode includes StrictConcurrency and the rest of the Swift 6 set, not ExistentialAny.

open as a page

When a team picks Swift instead of Objective-C for a new iOS module, which language differences matter most, and what does mixing the two cost?

level: middleimportance: should knowfreq 55%
basics
~20 s

Swift makes absence a type (Optional), gives String, Array and Dictionary value semantics, has full generics, calls struct methods directly and reports errors with throws. Objective-C sees only Swift declarations representable in Objective-C, so Swift-only types stay hidden from it.

open as a page