Member-only story
Swift Programming Tutorial: Extensions
Extend functionality effortlessly with Swift extensions
3 min readNov 25, 2024
Think of an extension as a way to say, “Hey, I love this class/struct/enum/protocol, but it could really use a glow-up.” It’s like adding cool accessories to an already nice car. Extensions let you slap on new features (methods, computed properties, etc.) to types you don’t own or don’t want to modify directly.
Why are extensions cool?
- No peeking into the source code: You can extend a type even if you don’t have access to its original definition. Like, ever tried to change how
String
works? You can’t (Apple wouldn’t let you). But with extensions, you can add functionality to it. - Keep your code clean: Extensions help you organize your code. Want to group methods that all deal with, say, a
Date
type? Toss 'em in an extension. Clean. Tidy. Marie Kondo-approved. - It’s like duct tape for types: Need a type to have a new trick but don’t want to create a whole new subclass or wrapper? Extensions got you covered.
This article is part of my Swift Programming Tutorial series.
What can you do with an extension?
Here’s where it gets spicy! You can:
- Add new methods.