You know that feeling when you write a code, only to realize later, there was a one-liner that could’ve done the same job? Yeah, me too.
Swift is full of underrated gems.
So here are 7 Swift hacks you’ll wish you knew sooner.
1. Format Numbers Without the Extra Work
Manually formatting numbers? Nope. Swift has a built-in way:
let formatted = NumberFormatter.localizedString(from: 1234567, number: .decimal)
print(formatted) // "1,234,567"
Works for currency, percentages, and scientific notation too.
2. The 'One-Liner' if let
Trick
Before:
if let username = username {
print(username)
}
Now:
username.map { print($0) }
Why? Cleaner, more functional, and no unnecessary nesting.
3. Force a SwiftUI View to Refresh Instantly
SwiftUI sometimes just… doesn’t refresh when you expect it to. Instead of overcomplicating state management, do this:
someStateVariable.toggle() // Forces view to re-render
No extra logic, no unnecessary bindings. Just works.
4. Auto-Resizing Text Fields Without Extra Code
Tired of writing logic for resizing text fields? Here’s the fix:
TextField("Enter text", text: $text)
.frame(minHeight: 40)
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(10)
What happens? The field grows/shrinks dynamically. No extra logic needed.
5. Turn a Dictionary into a URL Query String Instantly
No need to manually construct query strings. This one-liner handles it:
let params = ["search": "Swift Hacks", "limit": "10"]
let query = params.map { "\($0.key)=\($0.value)" }.joined(separator: "&")
print(query) // "search=Swift Hacks&limit=10"
Time saved. Code cleaner.
6. Ditch the Long if
Statements with switch
Instead of multiple conditions, simplify it like this:
switch value {
case 1...10: print("Low")
case 11...20: print("Medium")
case 21...: print("High")
default: print("Unknown")
}
Easier to read. Faster to debug.
7. Lazy-Load Expensive Functions
Instead of executing an expensive function right away, delay it:
func fetchData(_ loader: @autoclosure () -> String) {
print("Fetching Data: \(loader())")
}
fetchData(expensiveFunctionCall()) // Runs only when needed
Performance boost, especially in bigger apps.
That’s it—7 Swift hacks to simplify your code and speed up your workflow.
Hope this helps!
Top comments (0)