Master Swift Programming with 50 free flashcards. Study using spaced repetition and focus mode for effective learning in Programming.
An Optional in Swift represents a variable that can hold either a value or nil. It is declared using a ? after the type, e.g., var name: String?. Optionals enforce safe handling of the absence of a value at compile time.
You use optional binding with if let:if let unwrapped = optionalValue {
print(unwrapped)
}
This safely unwraps the optional and binds its value to a new constant within the block's scope.
Optional chaining uses ?. and returns nil if the optional is nil, failing gracefully.
Forced unwrapping uses ! and crashes at runtime if the optional is nil.
Example: person?.name vs person!.name
The nil-coalescing operator ?? provides a default value when an optional is nil.
Example: let name = optionalName ?? "Unknown"
If optionalName is nil, name is set to "Unknown".
An implicitly unwrapped optional is declared with ! instead of ?, e.g., var name: String!. It is automatically unwrapped when accessed, but will crash if it is nil. Used when a value is guaranteed to exist after initialization.
A Protocol defines a blueprint of methods, properties, and other requirements for a particular task.
Example:protocol Drawable {
func draw()
}
Classes, structs, and enums can conform to protocols by implementing the required members.
You use a protocol extension:protocol Greetable {
func greet()
}
extension Greetable {
func greet() { print("Hello!") }
}
Conforming types inherit the default but can override it.
Protocol composition lets you require a type to conform to multiple protocols using the & operator.
Example: func process(item: Codable & Hashable)
The parameter must conform to both Codable and Hashable.
A closure is a self-contained block of functionality that can be passed around and used in your code. Its syntax is:{ (parameters) -> ReturnType in
statements
}
Closures can capture and store references to variables from their surrounding context.
Trailing closure syntax allows you to write a closure argument after the function call's parentheses when it is the last parameter.
Example:numbers.sorted { $0 < $1 }
instead of numbers.sorted(by: { $0 < $1 }).
The @escaping attribute indicates that a closure can outlive the function it is passed to, e.g., stored in a property or called asynchronously.func fetch(completion: @escaping (Data) -> Void)
Non-escaping closures (the default) cannot be stored or called after the function returns.
A capture list defines how values are captured inside a closure, helping prevent retain cycles.
Syntax: { [weak self, unowned manager] in ... }[weak self] – captures self as a weak optional[unowned self] – captures self without increasing the reference count
Flashcards
Flip to reveal
Focus Mode
Spaced repetition
Multiple Choice
Test your knowledge
Type Answer
Active recall
Learn Mode
Multi-round mastery
Match Game
Memory challenge