Swift Programming
103 flashcards by MentisLibrary
Swift for app and server developers: optionals and safe unwrapping, structs, enums and value semantics, protocol-oriented design with generics, closures and capture lists, ARC, error handling, and async/await with actors.
- let versus var
- let binds a constant that cannot be reassigned after initialisation; var binds a variable. Both infer their type from the initial value.
- How much type annotation does Swift require?
- Almost none for locals: the type is inferred from the initialiser. Annotations are required when there is no initialiser, and for stored properties without a default.
- Why does let total = count + price fail when count is Int and price is Double?
- Swift performs no implicit numeric conversion. Mixed arithmetic requires an explicit conversion that names the target type.
- How is string interpolation written in Swift?
- \(expression) inside a string literal. The expression can be any value; Swift renders it through CustomStringConvertible or the default description.
- What makes a Swift switch different from C's?
- It must be exhaustive, there is no implicit fallthrough, and a case can match ranges, tuples, types and conditions with where.
- How do 0..<n and 0...n differ?
- ..< is a half-open range that excludes the upper bound; ... is closed and includes it. Both are real values you can pass around.
- What are argument labels, and how do you remove one?
- The label is the name at the CALL site; the parameter name is used inside the body. Writing _ as the label omits it.
- What does defer do?
- Schedules a block to run when the current scope exits, no matter how it exits. Several defer blocks run in reverse order of declaration.
- What is a computed property, and how does it differ from a stored one?
- A computed property has no storage; its get runs on every access and an optional set writes through to other state.
- What do willSet and didSet observe?
- They run before and after a STORED property changes. willSet receives newValue, didSet receives oldValue.
- What does lazy var do?
- Delays computing the property's initial value until the first access, then stores it.
- What is Swift's default access level, and what are the others?
- internal, visible everywhere in the module. The others are private (enclosing declaration and its extensions in the same file), fileprivate, public, and open which additionally allows subclassing outside the module.
- What is an optional, really?
- An enum: Optional<Wrapped> with cases .none and .some(Wrapped). String? is sugar for Optional<String> and nil is .none.
- What does force unwrapping with ! do when the value is nil?
- Traps immediately and terminates the process. There is no exception to catch.
- How does if let unwrap an optional?
- It binds the wrapped value to a new constant for the body when the optional is non-nil. Since Swift 5.7 the shorthand if let name reuses the same name.
- When do you choose guard let over if let?
- When the missing value means this scope cannot continue. guard binds for the REST of the scope and its else block must exit.
- What does ?? do?
- Returns the wrapped value if the optional is non-nil, otherwise the right-hand default. The right side is evaluated lazily, only when needed.
- What does optional chaining with ?. return?
- An optional of whatever the call would have produced. If any link is nil, the whole expression is nil and the rest is not evaluated.
- What is an implicitly unwrapped optional, and when is it justified?
- String! is an optional that unwraps automatically at each use. It exists mainly for values set immediately after initialisation, such as interface outlets.
- What do map and flatMap do on an Optional?
- map applies the transform to the wrapped value and keeps the result optional. flatMap does the same but collapses a nested optional result into one level.
- What is the core difference between a struct and a class?
- A struct is a value type: assignment and passing copy it, and each copy is independent. A class is a reference type: copies share one instance and are managed by ARC.
- What initialiser does a struct get for free?
- A memberwise initialiser taking every stored property in declaration order, plus a no-argument one if all properties have defaults. Properties with defaults may be omitted at the call site.
- What does mutating mean on a struct method?
- It declares that the method changes self. Without it, assigning to a property inside the method is a compile error, and it cannot be called on a let value.
- What can an enum carry beyond its case names?
- Raw values of a single literal type, associated values that differ per case, methods, computed properties and protocol conformances.
- What does CaseIterable give an enum, and what is its limit?
- A static allCases collection in declaration order. It can be synthesised only for enums with no associated values.
- How do raw values work on an enum?
- Declare a raw type after the name. Each case gets a rawValue, and a failable init?(rawValue:) maps back from the underlying value.
- What does indirect do on an enum?
- Adds a level of indirection so a case can hold the enum itself, which a plain value type cannot because its size would be unbounded.
- When does Swift synthesise Equatable and Hashable?
- When you declare the conformance and every stored property (or associated value) already conforms. No implementation is needed.
- What does Codable conformance give you?
- Codable is Encodable & Decodable. Conformance is synthesised when every stored property is Codable, and CodingKeys renames or omits fields.
- How do you compare two class instances for identity versus equality?
- === and !== compare references. == compares values and requires an Equatable conformance you write or synthesise.