swiftbeginner
Swift Basics
Variables, optionals and functions
6 questions
By EZ4Code Team
1. What are the keywords for declaring constants and variables?
let declares a constant, var declares a variable
const declares a constant, var declares a variable
let declares a variable, const declares a constant
var declares a constant, let declares a variable
Explanation: let declares a constant (immutable); var declares a variable (mutable); Swift recommends using let by default and only using var when modification is needed.
2. What is the purpose of the Optional type?
Represents that a value may be nil, enforcing type-safe handling of missing values
Indicates an optional variable
Represents a constant
Represents a global variable
Explanation: Optional<T> represents a value that may be nil, declared with ?; you must unwrap before access (! forced or ?? optional chaining), avoiding null pointer errors at the source.
3. What is the difference between forced unwrapping (!) and optional unwrapping (?)?
! force-unwraps and crashes if nil; ? is used for optional chaining and safely returns nil
They are exactly the same
? crashes
! is safe unwrapping
Explanation: ! force-unwraps and triggers a runtime error when the value is nil; ? with optional chaining safely returns nil instead of crashing when encountering nil.
4. What does if let do?
Safely unwraps an optional, binding to a constant and entering the branch when there is a value
Declares a variable
A loop statement
A type assertion
Explanation: if let constant = optional { } unwraps and assigns to constant when optional has a value, entering the if branch; otherwise enters the else branch.
5. What is the characteristic of guard let?
Used for early exit; the unwrapped constant is available in the subsequent scope
Can only be used in loops
The unwrapped constant is only available inside the guard block
Cannot be used with optionals
Explanation: guard let x = optional else { return } requires the condition to hold to continue; the unwrapped x is available in the subsequent scope, improving readability.
6. What is the syntax for default parameters in Swift functions?
func foo(x: Int = 10) { }
func foo(x: Int := 10) { }
func foo(Int x = 10) { }
func foo(x := 10) { }
Explanation: Swift function parameters use the format parameterName: Type = defaultValue, e.g. x: Int = 10; parameters with default values can be omitted when calling.