Skip to main content

Posts

Swift Optionals under the hood

In Swift, an Optional is a way to say “this value might be there, or it might be missing.” We use ? to show that a value is optional, like: var name: String? But what is really happening behind the scenes? What an Optional Really Is Inside Swift, an Optional is just a simple enum with two cases: enum Optional<Wrapped> { case none // no value case some(Wrapped) // has a value } That’s all an Optional is! So when you write: var age: Int? Swift actually thinks: var age: Optional<Int> The ? is only a shortcut for us. Why Optionals Feel Special Even though Optionals are simple, Swift gives them extra features: if let and guard let value ?? defaultValue value! for force unwrap a?.b?.c for optional chaining These special features work only with Swift’s built-in Optional. How Swift Stores Optionals Swift stores Optionals in a smart way: Many Optionals take no extra memory compared to the normal value. Swift uses unused bits or adds a small...

Understanding MVVM + Clean Architecture in SwiftUI

When building an iOS app, it's important to organize your code in a way that keeps things clean, testable, and easy to maintain. One of the best ways to do that is by combining MVVM (Model–View–ViewModel) with Clean Architecture . 1. Presentation Layer — The SwiftUI Frontline This is where your app interacts with the user . In SwiftUI, the View and ViewModel live in this layer. View (SwiftUI View): These are your UI screens — for example, ContentView , LoginView , or ProfileView . SwiftUI Views are simple and reactive. They observe data and automatically update the UI when something changes. struct ContentView: View { @StateObject var viewModel = ContentViewModel() var body: some View { VStack { if viewModel.isLoading { ProgressView() } else { List(viewModel.items) { item in Text(item.title) } } } .onAppear { viewModel.fetchItems() } ...

Understanding Task { }, Task.detached { }, and Task { @MainActor in … } in Swift Concurrency

Swift’s concurrency model introduced a cleaner and safer alternative to GCD. But with this came a common confusion: When should I use Task {} , Task.detached {} , and Task { @MainActor in ... } ? If you’ve ever wondered which one to pick, this article will clear it up with simple explanations and real-world guidance.

Understanding Copy-on-Write in Swift & Why It Matters in SwiftUI

  When you start building apps in Swift or SwiftUI, you’ll often hear the term “Copy-on-Write” — or CoW for short. It sounds fancy, but the idea is actually very simple and smart. Let’s break it down. Swift uses value types like struct , Array , Dictionary , and String . Normally, when you copy a value type, you’d expect it to create a new copy in memory. But copying big data every time can be slow and wasteful. So Swift uses a trick called Copy-on-Write — it pretends to copy the data, but it doesn’t actually do it until you change something. var numbers = [1, 2, 3] var moreNumbers = numbers  // No real copy yet! moreNumbers.append(4)      // Now Swift makes a real copy here. At first, both variables share the same data. Only when you modify moreNumbers, Swift creates a separate copy so that the original numbers stays safe. This is how Swift gives you safe, independent data but still keeps things fast and memory-friendly. How It Connects to SwiftUI Now he...

Benefits of Swift Testing over XCTest

If you’ve been building apps in Swift for a while, you’ve probably spent some time writing tests with  XCTest . It’s been the default testing framework on Apple platforms for years, and while it does the job, it often feels… a little clunky. Now enter Swift Testing — a newer, more modern testing framework that’s part of the Swift open-source project. The difference is immediately noticeable. Writing tests with Swift Testing feels like writing Swift code, not fighting a bunch of boilerplate. Here are some of the reasons why many developers are starting to prefer Swift Testing over XCTest: 1. The Syntax Just Flows Better In XCTest, you’re constantly reaching for XCTAssertEqual , XCTAssertTrue , XCTAssertNil , and so on. Each one has its own function, and you need to remember which is which. In Swift Testing, you simply use #expect with plain Swift expressions: #expect(result == 42) Compare that to: XCTAssertEqual(result, 42) Not a huge difference in one line, but when you multiply ...

Cached Async Image in SwiftUI

 SwiftUI’s AsyncImage is handy, but every time your view appears, it refetches the image—leading to flicker, delays, and unnecessary network use. What if you could fetch once, then reuse instantly? That's exactly what the Cached Async Image  delivers: a memory-powered caching layer that keeps SwiftUI image loading smooth, snappy, and resilient. First a simple in-memory cache without disk persistence. This will be thread-safe and auto-purges under memory pressure. A Singleton wrapping NSCache for URL → UIImage caching as follows : final class ImageCache {   static let shared = ImageCache()   private init() {}   private let cache = NSCache<NSURL, UIImage>()   func image(for url: URL) -> UIImage? {     cache.object(forKey: url as NSURL)   }   func insertImage(_ image: UIImage?, for url: URL) {     guard let image else { return }     cache.setObject(image, forKey: url as NSURL)   }   func clearAll() { ...

Atomic Design Pattern in SwiftUI

Atomic Design is a methodology for creating design systems with a clear, consistent hierarchy. It was introduced by Brad Frost and is inspired by chemistry. The core idea is to break down UI components into the smallest possible parts (atoms) and compose them to build more complex components and pages. Atomic Design Hierarchy 1. Atoms 
The basic building blocks of UI — buttons, labels, text fields, icons, colors, spacing units.
Example: PrimaryButton, AppText, Icon 2. Molecules 
 Groupings of atoms that form simple components.
Example: SearchBar = TextField + Icon, LabeledSwitch 3. Organisms 
 Relatively complex, standalone components made of atoms and molecules.
Example: LoginForm, UserCard, HeaderView 4. Templates 
 Layouts or skeletons that define the structure of pages using organisms.
Example: AuthScreenTemplate, DashboardTemplate 5. Pages 
 Final screens with real data/content, composed of templates.
Example: LoginScreen, SettingsScreen. Here is how an example folders structure l...

Popular posts from this blog