What the meaning of question mark '?' in swift?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
The question mark ? in Swift serves multiple purposes, all related to handling values that might be absent. It declares optional types (Int?), enables optional chaining (object?.property), provides nil-coalescing defaults (value ?? fallback), performs conditional casting (as?), and marks failable initializers (init?). Understanding these uses is fundamental to Swift because optionals are the language's primary mechanism for null safety — they replace null pointer exceptions with compile-time checks.
Declaring Optionals
An optional is a wrapper that either contains a value or contains nil. String? is syntactic sugar for Optional<String>.
Unwrapping Optionals
Optional Binding with if let
Guard let (Early Exit)
Force Unwrapping with !
Force unwrapping is unsafe and should be used only when you are certain the value is not nil.
Optional Chaining
The ? enables safe access to properties, methods, and subscripts on optional values:
If any link in the chain is nil, the entire expression evaluates to nil without crashing.
Nil-Coalescing Operator (??)
?? returns the left side if it is not nil, otherwise returns the right side.
Conditional Casting (as?)
as? is the safe cast operator. Use as! for force casting (crashes if the cast fails).
Failable Initializers (init?)
Standard library examples include Int("hello") which returns Int? — nil if the string is not a valid integer.
Implicitly Unwrapped Optionals (!)
Implicitly unwrapped optionals are used when a value is nil initially but is guaranteed to have a value before first use (like @IBOutlet connections set during view loading).
Optional Map and FlatMap
Common Pitfalls
- Force unwrapping (
!) without checking for nil: This is the most common cause of Swift runtime crashes. Always useif let,guard let, or??instead of!unless you have absolute certainty the value exists. - Confusing
?(optional) with!(implicitly unwrapped):String?requires explicit unwrapping.String!auto-unwraps but still crashes on nil. Use!declarations only for outlets and cases where the value is guaranteed after initialization. - Optional chaining returning an optional:
person.address?.cityreturnsString?, notString. If you need a non-optional, combine with??orif let. - Comparing optionals to nil instead of using if let:
if name != nil { print(name!) }forces an unwrap.if let name = name { print(name) }is safer and more idiomatic. - Nested optionals (
Int??): Chaining operations on optionals can produce double-wrapped optionals. UseflatMapinstead ofmapto avoidOptional(Optional(value)).
Summary
Type?declares an optional that can hold a value or nilif letandguard letsafely unwrap optionals without risk of crashes?.(optional chaining) safely accesses properties on optional values, returning nil if any link is nil??(nil-coalescing) provides a default value when an optional is nilas?performs safe type casting that returns nil on failure- Avoid force unwrapping (
!) except when you are certain the value is not nil
Related reading
- What to do on TransactionTooLargeException
- What to use instead of addPreferencesFromResource in a PreferenceActivity?
- What values should I use for CFBundleVersion and CFBundleShortVersionString?
- What version of mobile safari comes with each version of iOS?
- What's a redirect URI? how does it apply to iOS app for OAuth2.0?
- What's a reliable way to make an iOS app crash?
- What's a simple way to get a text input popup dialog box on an iPhone
- What''s ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES with CocoaPods, Swift 3 and Xcode 8
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.