Extensions add methods, computed properties, and protocol conformances to existing types—even types you do not own, like String or Foundation types.
Syntax
extension String {
var isEmailLike: Bool { contains("@") }
}
extension Int {
func squared() -> Int { self * self }
}
Organizing code
Split large types across files with extensions grouped by protocol conformance—cleaner than monolithic class files.
Important interview questions and answers
- Q: Extension vs subclass?
A: Extensions cannot add stored properties or override; they augment behavior without changing inheritance. - Q: Can extensions add protocol conformance?
A: Yes—retroactive modeling lets you adapt third-party types to your protocols.
Self-check
- Can extensions add stored properties?
- Can you extend types from other modules?
Pitfall: Extensions cannot add stored properties—only methods and computed properties.
Interview prep
- Stored properties in extensions?
No—only methods and computed properties.
- Retroactive modeling?
Extend third-party types to conform to your protocols.