DEV Community

Cover image for 7 Swift Hacks You Wish You Knew Sooner
Balraj Singh
Balraj Singh

Posted on

7 Swift Hacks You Wish You Knew Sooner

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"
Enter fullscreen mode Exit fullscreen mode

Works for currency, percentages, and scientific notation too.

2. The 'One-Liner' if let Trick

Before:

if let username = username {
    print(username)
}
Enter fullscreen mode Exit fullscreen mode

Now:

username.map { print($0) }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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")
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)