Generated by All in One SEO v5.0.0.1, this is an llms.txt file, used by LLMs to index the site. # Livsy Code Learn Swift the smart way ## Sitemaps - [XML Sitemap](https://livsycode.com/sitemap.xml): Contains all public & indexable URLs for this website. ## Posts - [Reading Concentric Corner Radii with GeometryProxy in SwiftUI](https://livsycode.com/swiftui/reading-concentric-corner-radii-with-geometryproxy-in-swiftui/) - Greetings, traveler! SwiftUI can create shapes whose corners follow the curvature of their container. ConcentricRectangle handles this automatically, but sometimes you need the calculated radius values themselves. In iOS 27, GeometryProxy provides two APIs for this: What concentric corners are Two rounded rectangles have concentric corners when their curves share the same center point. Consider - [The iOS Perceived Performance Agent Skill](https://livsycode.com/best-practices/the-ios-perceived-performance-agent-skill/) - Greetings, traveler! AI agent skills are reusable instructions that teach an agent how to handle a specific type of task. They can define its focus, workflow, constraints, and reference materials, so the agent does not need to approach every request from scratch. This article is part of a series about building practical AI agent skills - [The iOS Testing Strategy Agent Skill](https://livsycode.com/best-practices/the-ios-testing-strategy-agent-skill/) - Greetings, traveler! Agent Skills are reusable instruction packages that teach an AI coding agent how to handle a specific type of task. A skill can define a workflow, decision rules, constraints, and reference material that the agent loads when needed. This article is part of my series about creating practical Agent Skills for iOS development. - [Foundation Models Utilities](https://livsycode.com/swift/foundation-models-utilities/) - Greetings, traveler! Apple’s Foundation Models framework provides a Swift API for working with language models through sessions, tools, structured output, and dynamic instructions. Apple has now published a separate open-source package called Foundation Models framework utilities that adds several experimental components on top of that framework. The package focuses on three areas: connecting LanguageModelSession to hosted - [Building an Animated Character in SwiftUI](https://livsycode.com/swiftui/building-an-animated-mascot-character-in-swiftui/) - Greetings, traveler! Mascot characters work well in apps that need a little warmth. They are especially useful when the app has quiet moments: an empty state, a waiting screen, a habit tracker, a pet project, a learning app, a finance app with onboarding, or anything that could otherwise feel too static. A small animated character - [Continuation vs CheckedContinuation vs UnsafeContinuation in Swift](https://livsycode.com/swift/continuation-vs-checkedcontinuation-vs-unsafecontinuation-in-swift/) - Greetings, traveler! Continuations are one of those Swift Concurrency APIs that most app developers do not touch every day, but they become important as soon as old callback-based code has to be wrapped into async/await. A typical example looks like this: func loadUser() async throws -> User { try await withCheckedThrowingContinuation { continuation in userService.loadUser - [Designing a Dynamic Retail Home Page on iOS](https://livsycode.com/best-practices/designing-a-dynamic-retail-home-page-on-ios/) - Greetings, traveler! I recently joined an iOS System Design podcast with Walid SASSI to discuss how to design a retail application with a dynamic, campaign-driven home page. The conversation followed the usual system design interview format: define the scope, agree on requirements, design the API and data flow, and then examine the parts where most - [NSTextTable in Swift](https://livsycode.com/uikit/nstexttable-in-swift/) - Greetings, traveler! With the iOS 27 SDK, Apple brought NSTextTable, NSTextTableBlock, and related TextKit APIs to UIKit. These classes have existed in AppKit for years, but iOS developers can now use them directly to build real tables inside NSAttributedString. This is not another table view. Instead, it extends the rich text model, making tables part - [The Xcode 27 Agent Skills](https://livsycode.com/best-practices/the-xcode-27-agent-skills/) - Greetings, traveler! AI agent skills are reusable sets of instructions that teach an agent how to handle a particular type of task. A skill can define what the agent should inspect, which workflow it should follow, what constraints it must respect, and which reference material it should use. You can read more about it here. - [The iOS Launch Performance Agent Skill](https://livsycode.com/swiftui/ios-launch-performance-agent-skill/) - Greetings, traveler! AI agent skills are reusable instructions that teach an agent how to handle a specific kind of task. They can define the focus, workflow, constraints, and references the agent should use instead of starting from scratch every time. This article is part of a series about building practical skills for iOS development. The - [Modern iOS Performance Myths: Episode 1](https://livsycode.com/swiftui/modern-ios-performance-myths-episode-1/) - Greetings, traveler! I recently joined Swift Academy for a podcast episode about iOS performance. The episode is called "Modern iOS Performance Myths", hosted by Walid Sassi, and I had a great discussion there together with Bogdan Poplauschi. The conversation became bigger than we expected, so we split it into two episodes. What we discussed in - [An Xcode Agent Prompt: What It Signals for Combine and RxSwift](https://livsycode.com/swift/an-xcode-agent-prompt-what-it-signals-for-combine-and-rxswift/) - Greetings, traveler! While poking around Xcode’s agent prompts, people noticed a blunt instruction: Avoid using the Combine framework and instead prefer to use Swift’s async and await versions of APIs instead. That reads harsher than the older guidance many of us saw last year, which said: In general, prefer the use of Swift Concurrency (async/await, - [What is Swift Concurrency?](https://livsycode.com/swift/what-is-swift-concurrency/) - Greetings, traveler! Swift Concurrency was introduced to address a long-standing problem in application development: writing concurrent code that remains correct as systems grow in complexity. Coordinating work across threads has traditionally relied on conventions and discipline, which makes mistakes easy to introduce and difficult to detect. The language provided tools to perform concurrent work, but - [AI Agent Skills for iOS Development](https://livsycode.com/best-practices/ai-agent-skills-for-ios-development/) - Greetings, traveler! AI coding agents are no longer just autocomplete with a chat box. Tools like Codex and Claude Code can read a repository, edit files, run commands, inspect failures, and continue working across multiple steps. That sounds useful until the agent starts making the same wrong assumption for the fifth time. In an iOS - [The SwiftUI Performance Skill](https://livsycode.com/swiftui/the-swiftui-performance-skill/) - Greetings, traveler! AI agent skills are small instruction packages that teach an agent how to work in a specific area. They can describe rules, workflows, project conventions, review checklists, references, and examples. In practice, a skill turns general AI assistance into something more focused. This article is part of the series about agent skills. If - [Image Playground Sheet in SwiftUI](https://livsycode.com/swiftui/image-playground-sheet-in-swiftui/) - Greetings, traveler! When the Image Playground framework first appeared, it gave developers two different paths. You could present the system Image Playground interface, or you could use ImageCreator to generate images programmatically from your app. That second path is going away. Apple has deprecated the ImageCreator class. It will no longer work in iOS 27, - [Changing the shape of glass buttons in SwiftUI](https://livsycode.com/swiftui/changing-the-shape-of-glass-buttons-in-swiftui/) - Greetings, traveler! iOS 26 added new Liquid Glass APIs to SwiftUI, including a new button style: Button { // Action } label: { Image(systemName: "sun.max") } .buttonStyle(.glass)Button { // Action } label: { Image(systemName: "sun.max") } .buttonStyle(.glass) It is a small API, but it changes the default look of system buttons quite a lot. Instead - [A Custom Pull-to-Refresh in SwiftUI](https://livsycode.com/swiftui/a-custom-pull-to-refresh-in-swiftui/) - Greetings, traveler! SwiftUI provides a built-in .refreshable modifier, which covers the majority of use cases. At some point, product requirements start to demand more control over the refresh interaction. Custom animations, branded indicators, precise control over gesture thresholds, and coordination with complex layouts are typical examples. In these cases, a custom pull-to-refresh component becomes a - [Swift 6.4 adds async support to Result](https://livsycode.com/swift/swift-6-4-adds-async-support-to-result/) - Greetings, traveler! Swift has had Result.init(catching:) for a long time. It is a small convenience initializer that runs a throwing closure and stores the outcome as a value. If the closure returns successfully, you get .success. If it throws, you get .failure. That worked nicely for synchronous code. let result = Result { try decodeUser(from: - [Rotating Liquid Glass in SwiftUI without breaking the shape](https://livsycode.com/swiftui/liquid-glass-rotating/) - Greetings, traveler! Have you ever tried to apply rotationEffect to a SwiftUI view that already has glassEffect? The code looks innocent: This happens because Liquid Glass is more geometry-sensitive than a simple background. It is not just a color or a blur behind the text. SwiftUI anchors the Liquid Glass effect to the bounds of - [_UIPortalView: From Live Mirroring to Liquid Glass-Style Effects](https://livsycode.com/uikit/exploring-_uiportalview-live-view-replication-without-copying-or-snapshots/) - Greetings, traveler! I recently spent some time studying one of the more interesting private UIKit components: _UIPortalView. Sometimes you want the same visual content to appear in more than one place on the screen, while keeping the original view alive, interactive, and continuously updated. This kind of requirement appears in many UI effects: A picture-in-picture - [anyAppleOS in Swift 6.4](https://livsycode.com/swift/swift-6-4-adds-anyappleos-for-cleaner-availability-checks/) - Greetings, traveler! Availability checks in Swift are usually clear when the API belongs to one platform. @available(iOS 26.0, *) func useNewiOSFeature() { // ... }@available(iOS 26.0, *) func useNewiOSFeature() { // ... } The code gets noisier when the same API is available across Apple's platforms at the same OS version. @available(macOS 26.0, iOS 26.0, - [Async cleanup in defer with Swift 6.4](https://livsycode.com/swift/async-cleanup-in-defer-with-swift-6-4/) - Greetings, traveler! Swift developers have used defer for years to guarantee cleanup when a scope exits. It works well for releasing resources, unlocking locks, or resetting state. One limitation remained: asynchronous cleanup could not live inside a defer block. If a cleanup operation required await, developers had to duplicate cleanup code across multiple exit paths - [Adaptive TabView Layouts with .tabViewStyle(.sidebarAdaptable) in SwiftUI](https://livsycode.com/swiftui/adaptive-tabview-layouts-with-tabviewstyle-sidebaradaptable-in-swiftui/) - Greetings, traveler! SwiftUI tabs used to be simple on iPhone and more awkward on iPad. On iPhone, TabView naturally mapped to a bottom tab bar. On iPad, many apps needed something closer to a sidebar: more space, grouped destinations, and a layout that feels better on a large display. The usual answer was to build - [withTaskCancellationShield in Swift 6.4](https://livsycode.com/swift/task-cancellation-shields-in-swift-6-4/) - Greetings, traveler! Swift cancellation is cooperative. A task can be cancelled, but Swift does not stop it by force. Your code has to observe cancellation explicitly: Task.isCancelled try Task.checkCancellation()Task.isCancelled try Task.checkCancellation() Most of the time, this is exactly what you want. If the user leaves the screen, the network request can stop. If a parent - [SwiftUI ContentBuilder: one builder name for different content](https://livsycode.com/swiftui/swiftui-contentbuilder-one-builder-name-for-different-swiftui-content/) - Greetings, traveler! SwiftUI now has a new ContentBuilder attribute. The declaration is small: typealias ContentBuilder = ViewBuildertypealias ContentBuilder = ViewBuilder So this is not a completely separate result builder. Apple documents ContentBuilder as a type alias for ViewBuilder. But the name is the interesting part. ViewBuilder always sounded tied to views. SwiftUI has grown beyond - [toolbarMinimizeBehavior in SwiftUI](https://livsycode.com/swiftui/toolbarminimizebehavior-in-swiftui/) - Greetings, traveler! SwiftUI has a new modifier for controlling how a toolbar behaves while the user scrolls: Apple shows this exact pattern with a ScrollView: ScrollView { StickerListView() } .toolbarMinimizeBehavior(.onScrollDown, for: .navigationBar)ScrollView { StickerListView() } .toolbarMinimizeBehavior(.onScrollDown, for: .navigationBar) How it works The modifier is defined on View: nonisolated func toolbarMinimizeBehavior( _ behavior: ToolbarMinimizeBehavior, for bars: - [NavigationTransition.crossFade in SwiftUI](https://livsycode.com/swiftui/navigationtransition-crossfade-in-swiftui/) - Greetings, traveler! SwiftUI gets a new built-in navigation transition in iOS 27: NavigationTransition.crossFade. It is a navigation transition that cross-fades between the appearing view and the disappearing view. The declaration is simple: static var crossFade: CrossFadeNavigationTransitionstatic var crossFade: CrossFadeNavigationTransition You apply it with the existing navigationTransition(_:) modifier: .navigationTransition(.crossFade).navigationTransition(.crossFade) Where it fits crossFade belongs to NavigationTransition, - [SwiftUI drag containers in iOS 27](https://livsycode.com/swiftui/swiftui-drag-containers-in-ios-27/) - Greetings, traveler! iOS 27 adds a new layer to SwiftUI drag and drop: drag containers. At first glance, it looks like another variation of .draggable. But the model is different. Instead of giving every draggable view its full payload, you can give the view only an identifier. The container then turns those identifiers into real Transferable - [SwiftUI reorderable containers in iOS 27](https://livsycode.com/swiftui/swiftui-reorderable-containers-in-ios-27/) - Greetings, traveler! If your UI was a List, you had a pretty clear path with onMove. If your UI was a grid, a stack, or a custom layout, you usually had to solve it yourself. In iOS 27, SwiftUI gets a new API for this: reorderable() and reorderContainer(for:isEnabled:move:). The interesting part is not just that we - [SwiftUI's @State is now a macro](https://livsycode.com/swiftui/swiftuis-state-is-now-a-macro/) - Greetings, traveler! Apple's documentation for State has a new shape. It now shows State() as an attached macro: @attached(accessor, names: named(init), named(get), named(set)) @attached(peer, names: prefixed(`_`), prefixed(__), prefixed(`$`)) macro State()@attached(accessor, names: named(init), named(get), named(set)) @attached(peer, names: prefixed(`_`), prefixed(__), prefixed(`$`)) macro State() That looks like a much bigger change than it feels in actual SwiftUI code. - [AsyncImage and HTTP caching in iOS 27](https://livsycode.com/swiftui/asyncimage-and-http-caching-in-ios27/) - Greetings, traveler! When Apple introduced AsyncImage, it looked like the missing simple API for remote images in SwiftUI. And for simple screens, it was fine. You had a URL, SwiftUI loaded the image, and you could react to loading, success, and failure states through AsyncImagePhase. But there was always one uncomfortable detail: caching. For years, - [SwiftUI TabRole.prominent in iOS 27](https://livsycode.com/swiftui/swiftui-tabrole-prominent-in-ios27/) - Greetings, traveler! SwiftUI gets a new tab role in iOS 27: TabRole.prominent. You can mark one tab as visually prioritized within the tab hierarchy, and SwiftUI can give it a prominent treatment in supported tab bars. That sounds very close to a pattern many iOS developers wanted after the newer Liquid Glass tab bar design - [Swipe actions are no longer trapped inside List in SwiftUI](https://livsycode.com/swiftui/swipe-actions-are-no-longer-trapped-inside-list-in-swiftui/) - Greetings, traveler! swipeActions has always been closely associated with List. That was fine for many screens. If your UI was a classic settings page, inbox, notification list, or table-style screen, List gave you row gestures almost for free: List(messages) { message in MessageRow(message: message) .swipeActions { Button(role: .destructive) { delete(message) } label: { Label("Delete", systemImage: - [Why Your @Observable Class init() Runs Multiple Times in SwiftUI](https://livsycode.com/swiftui/why-your-observable-class-init-runs-multiple-times-in-swiftui/) - Greetings, traveler! SwiftUI encourages a lightweight view layer. Views are value types, rebuilt frequently, and expected to be cheap. This mental model becomes tricky when you start storing reference types in @State, especially after adopting the Observation framework (@Observable). Note By the way, SwiftUI’s @State is now a macro, which addresses some points raised in - [Reactive frameworks vs async/await vs AsyncAlgorithms](https://livsycode.com/best-practices/reactive-is-no-longer-the-default-in-swift/) - Greetings, traveler! There was a time when reactive programming felt like the natural answer to many iOS architecture problems. Before Swift Concurrency, asynchronous programming on Apple platforms was spread across many different mechanisms. A network request usually came with a completion handler. User interaction came through target-action, delegates, or closures. System events often arrived through - [UniqueBox, Ref, and MutableRef in Swift 6.4](https://livsycode.com/swift/uniquebox-ref-and-mutableref-in-swift-6-4/) - Greetings, traveler! Swift 6.4 continues the ownership work that has been building through noncopyable types, borrowing, consuming parameters, lifetime dependencies, Span, and MutableSpan. The important part of this direction is that Swift is gaining more ways to describe ownership and access rules directly in APIs, instead of leaving them as compiler internals, documentation comments, or - [A Feature Flags System in Swift](https://livsycode.com/best-practices/a-feature-flags-system-in-swift/) - Greetings, traveler! Feature flags are a foundational tool for modern mobile development. They allow teams to control behavior at runtime, roll out features gradually, run experiments, and decouple deployment from release. In iOS applications, a well-designed feature flag system also becomes a central coordination mechanism between product, QA, and engineering. This article walks through a - [Enum Cases as Protocol Witnesses in Swift](https://livsycode.com/best-practices/enum-cases-as-protocol-witnesses-in-swift/) - Greetings, traveler! Enums are one of the most useful modeling tools in Swift. We use them for screen states, navigation routes, user actions, errors, commands, feature flags, and many other parts of iOS applications. A lot of these models have something in common: they describe a closed set of possible values. A screen can be - [A Type-Safe EventBus in Swift](https://livsycode.com/best-practices/a-type-safe-eventbus-in-swift/) - Greetings, traveler! In larger iOS applications, communication between features often becomes harder than the feature itself. A service finishes an operation, a coordinator needs to react, several screens may need to refresh, and passing every dependency through the entire navigation tree quickly starts to feel like unnecessary plumbing. Dependency injection and state management still have - [How to Think About Performance in iOS](https://livsycode.com/best-practices/how-to-think-about-performance-in-ios/) - Greetings, traveler! Performance work in mobile apps often starts with a familiar question: why does this screen feel slow. The answer rarely sits in one place. It might be in the network, in the way the UI updates, in how data flows through the app, or in how memory is used under the hood. Looking - [Synchronization in Swift: Actors vs Queues vs Locks](https://livsycode.com/best-practices/actors-vs-queues-vs-locks-in-swift/) - Greetings, traveler! Concurrency in modern iOS applications shows up almost everywhere. Networking, database access, image processing, and even parts of UI logic often run in parallel. The system schedules work across multiple threads, and for the most part this happens transparently. The code compiles, the app runs, and everything looks fine until shared state enters - [An Odometer-Style Number Animation in SwiftUI](https://livsycode.com/swiftui/an-odometer-style-number-animation-in-swiftui/) - Greetings, traveler! Counters with a rolling, odometer-like feel are a familiar interaction pattern in modern interfaces. You can see this kind of visual treatment in products such as YouTube when numeric values update on screen. In SwiftUI, reaching a similar result is pleasantly straightforward because the framework already includes contentTransition(.numericText()), a transition designed specifically for - [A Reusable Spotlight Onboarding Component in SwiftUI](https://livsycode.com/swiftui/a-reusable-spotlight-onboarding-component-in-swiftui/) - Greetings, traveler! Onboarding often requires guiding users through a complex interface by highlighting specific elements and explaining their purpose. Many applications solve this with a dimmed background and a visible cutout around the focused control. While the visual effect looks simple, implementing it in a reusable and layout-safe way in SwiftUI requires careful coordination between - [Swift ARC: From Zombie Objects to Side Tables](https://livsycode.com/swift/swift-arc-from-zombie-objects-to-side-tables/) - Greetings, traveler! Reference counting is one of those topics every iOS developer learns early and then rarely revisits in depth. At the surface, it feels predictable: objects are retained, released, and eventually deallocated. Underneath, the implementation is far more nuanced. The way Swift manages memory has changed since its early versions, and those changes reflect - [Swift ARC: Interview Essentials](https://livsycode.com/swift/swift-arc-interview-essentials/) - Greetings, traveler! Automatic Reference Counting is one of those topics that almost every iOS developer has “used” for years and only occasionally revisits in detail. The surface model is simple: objects are released when their reference count reaches zero. The interesting part begins when you look at how the compiler and runtime cooperate to make - [Simplifying Data Access in SwiftUI with @dynamicMemberLookup](https://livsycode.com/swiftui/simplifying-data-access-in-swiftui-with-dynamicmemberlookup/) - Greetings, traveler! In SwiftUI architecture, it’s common to separate data and presentation logic using a Model, a ViewModel, and a View. The model holds your raw data, the view model prepares that data for display, and the view binds to the view model. But this layering introduces a small inconvenience: deep property access. If your - [SwiftUI withAnimation сompletion on iOS 13–16](https://livsycode.com/swiftui/swiftui-withanimation-completion-on-ios-13-16/) - Greetings, traveler! In iOS 17 Apple added withAnimation(_:completion:), and it feels like the obvious missing piece. On earlier versions, SwiftUI does not expose a completion callback for implicit animations. withAnimation only wraps state changes into an animation transaction. It is not an animation object you can observe, so there is nothing to “finish” from SwiftUI’s - [How I migrated 300 screens to SwiftUI and what I learned](https://livsycode.com/swiftui/how-i-migrated-300-screens-to-swiftui-and-what-i-learned/) - Greetings, traveler! At some point, we decided to move forward with a full redesign of the application. The scope was significant, and the plan included expanding the team to handle the expected workload. The timelines were tight, which forced us to look closely at the development process and identify potential bottlenecks early. UIKit quickly came - [Stack vs Heap in Swift](https://livsycode.com/swift/stack-vs-heap-in-swift-interview-essentials/) - Greetings, traveler! Questions about stack and heap come up regularly when discussing Swift memory model. The topic looks simple on the surface, yet many explanations stop at oversimplified rules that break down as soon as real code enters the picture. The most common shortcut sounds familiar: structs live on the stack, classes live on the - [Thread vs Queue vs Actor executor in Swift](https://livsycode.com/swift/thread-vs-queue-vs-actor/) - Greetings, traveler! Questions around concurrency often drift into terminology. Thread, queue, executor — the words sound related, and many explanations blur the boundaries between them. That usually works until the first real bug appears, and then the model falls apart. A more reliable way to approach this topic is to separate the concepts by responsibility. - [XCTest in iOS](https://livsycode.com/swift/xctest-in-ios-interview-essentials/) - Greetings, traveler! Unit testing often comes up in iOS interviews, yet many developers have limited hands-on experience with it. Some teams barely use tests, some cover only a narrow slice of the codebase, and some rely on a few integration checks while calling them unit tests. Interviewers know that. They usually care less about whether - [Rebuilding higher-order functions in Swift](https://livsycode.com/swift/rebuilding-higher-order-functions-in-swift/) - Greetings, traveler! On iOS interviews, candidates are often asked to reimplement familiar higher-order functions from scratch. These tasks look simple on the surface, yet they quickly reveal how well you understand generics, value semantics, and iteration over collections. I keep seeing variations of this question across different companies, and the exact function rarely matters as - [SwiftUI Custom Popover](https://livsycode.com/swiftui/swiftui-custom-popover/) - Greetings, traveler! SwiftUI gives you .popover, but sometimes it is the unsuitable tool. For instance, design might require a popover with no arrow. In those cases we can reach for matchedGeometryEffect. It lets you “attach” an overlay to a view without dealing with manual frames and coordinate spaces. We can also make it reusable. A - [Memento Design Pattern in Swift](https://livsycode.com/best-practices/memento-design-pattern-in-swift/) - Greetings, traveler! There are moments in almost every app where state matters more than behavior. A user edits a form, navigates across screens, makes a few changes, and then expects to undo everything with a single action. Reconstructing that state from scratch can be expensive or simply impractical. That is where the Memento pattern fits - [Infinite ScrollView in SwiftUI](https://livsycode.com/swiftui/infinite-scrollview-in-swiftui/) - Greetings, traveler! Some UI patterns expect a scroll view that never reaches an end. Think of a “featured” carousel on a storefront, a ticker of recent items, a carousel of songs in your player, or a background strip of logos in a landing screen. In these cases, the user should be able to keep swiping - [SwiftUI Week Calendar View. #6: Customization](https://livsycode.com/swiftui/swiftui-week-calendar-view-6-customization/) - Greetings, traveler! We continue our series about SwiftUI Week Calendar View. This is the last part, where we will add some customization options. If you just want to check out the complete source code, here it is. WeekView Let's start with the WeekView. There is nothing complex we can do. We can just pass values for - [How I decomposed a monolithic iOS app into 130+ modules and reduced build time by ~35%](https://livsycode.com/best-practices/how-i-decomposed-a-monolithic-ios-app-into-130-modules-and-reduced-build-time-by-35/) - Greetings, traveler! The application I joined had a long history. Development started around 2015, with a large Objective-C codebase that gradually evolved as different teams took ownership over the years. At some point Swift was introduced, but the transition relied on a bridging header, which kept both worlds tightly coupled. As the codebase changed hands, - [A vision for Networking in Swift](https://livsycode.com/swift/a-vision-for-networking-in-swift/) - Greetings, traveler! Swift Evolution recently published a vision document that looks at networking from a broader angle. It does not introduce a specific API or proposal. Instead, it outlines how networking in Swift could evolve over the next few years and what kind of foundation the ecosystem may move toward. The document lives in the - [Copy-On-Write in Swift: Semantics, Misconceptions, and a Custom Implementation](https://livsycode.com/swift/copy-on-write-in-swift-semantics-misconceptions-and-a-custom-implementation/) - Greetings, traveler! Swift developers encounter copy-on-write (COW) early when working with collections such as Array or String. These types behave like value types while internally sharing storage between copies. The technique allows Swift to preserve value semantics while reducing unnecessary memory duplication. Understanding how this mechanism works provides practical benefits. It clarifies how Swift collections - [iOS app launch process: from tap to first frame](https://livsycode.com/uikit/ios-app-launch-process-from-tap-to-first-frame/) - Greetings, traveler! There is a moment every iOS engineer has experienced but rarely examined in detail. You tap an app icon, and within a fraction of a second the interface appears, already interactive, already alive. That path from tap to first frame looks simple on the surface, yet it crosses several layers of the system, - [NSCache in Swift: A Practical Guide](https://livsycode.com/best-practices/nscache-in-swift-a-practical-guide/) - Greetings, traveler! Caching rarely looks like a hard problem—until an app starts rendering heavy feeds, repeatedly mapping rich text, or decoding the same assets on every scroll. At that point, the difference between “working” and “smooth” is often a cache layer placed in the right spot. On iOS, NSCache is a great fit for this - [Swift Abstractions: Generics, some, and any](https://livsycode.com/swift/swift-abstractions-generics-some-and-any/) - Greetings, traveler! When preparing for iOS interviews, developers eventually reach a group of questions that appear deceptively simple. Generics, protocols with associated types, existential types, and the keywords some and any often appear in that category. The syntax is familiar to most Swift engineers. The underlying model of the type system is where interviews become - [Xcode 26 Compilation Cache](https://livsycode.com/best-practices/xcode-26-compilation-cache/) - Greetings, traveler! Most iOS engineers don’t need another reminder that builds are expensive — we feel it every day. You change a few lines. You wait. You switch branches. You wait again. CI rebuilds the same targets for the tenth time today. Someone suggests cleaning DerivedData. The build gets slower, then faster, then weird again. - [Preventing SwiftUI .refreshable from Affecting Child ScrollViews](https://livsycode.com/swiftui/preventing-swiftui-refreshable-from-affecting-child-scroll-views/) - Greetings, traveler! SwiftUI’s .refreshable looks deceptively simple: attach it to a List or ScrollView, implement a refresh closure, and you get pull-to-refresh for free. However, there is a detail that often surprises developers the first time they build more complex view hierarchies: .refreshable is not scoped to a single scroll view. Under the hood, it - [How to map an optional Binding to a Boolean value, and why you might not want to do so](https://livsycode.com/best-practices/how-to-map-optional-binding-to-bool/) - We can create an extension to the optional Binding, which will accept nil as false. - [Mediator Design Pattern in Swift](https://livsycode.com/best-practices/mediator-design-pattern-in-swift/) - Greetings, traveler! We continue to discuss Design Patterns. It is the turn of another Behavioral Design Pattern, the Mediator. At first glance it feels similar to Observer. Or even to a simple service object. The difference only becomes clear when the system starts growing and objects begin talking to each other in too many directions. - [When SwiftUI modifiers hold onto memory longer than expected](https://livsycode.com/swiftui/when-swiftui-modifiers-hold-onto-memory-longer-than-expected/) - Greetings, traveler! Every experienced iOS engineer eventually runs into the same unsettling moment: you navigate back from a screen, expect deinit to fire, and nothing happens. The view disappears but the memory does not. In SwiftUI projects, this behavior has repeatedly surfaced around three modifiers: onSubmit, searchable, and refreshable. The pattern looks similar each time. - [GitHub-Like Contribution Chart in SwiftUI](https://livsycode.com/swiftui/github-like-contribution-chart-in-swiftui/) - In this tutorial, we'll create a GitHub-like contribution chart in SwiftUI for the habit-tracker app. This chart visualizes user progress over a given period - [Building a SwiftUI Toast in 5 Steps](https://livsycode.com/swiftui/building-a-toast-component-in-swiftui/) - Greetings, traveler! SwiftUI still doesn’t provide a native toast component. Alerts and sheets exist, but both are modal by design. A toast solves a different problem: it delivers short-lived feedback without interrupting the user’s flow. In this article, I’ll walk through a practical way to implement a toast in SwiftUI. The solution is lightweight, reusable, - [Array expression trailing closures in Swift](https://livsycode.com/swift/array-expression-trailing-closures-in-swift/) - Greetings, traveler! Swift’s syntax around trailing closures has steadily evolved over the years. For most types, writing Type { ... } feels natural and predictable. Until recently, however, arrays and dictionaries were a special case. If you tried to attach a trailing closure directly after an array or dictionary type expression, the parser refused to - [SwiftUI Text init with verbatim parameter](https://livsycode.com/swiftui/swiftui-text-init-with-verbatim-parameter/) - Greetings, traveler! When diving into SwiftUI development, one of the fundamental components you'll frequently interact with is Text. SwiftUI's Text initializer offers several ways to initialize text content. Today we will explore two of them: with the verbatim parameter and without it. Without verbatim The standard initializer for Text in SwiftUI looks like this: Text("Hello, - [Chain of Responsibility Design Pattern in Swift](https://livsycode.com/best-practices/chain-of-responsibility-design-pattern-in-swift/) - Greetings, traveler! We continue to learn about Design Patterns. We have started to explore Behavioral Patterns, and the first one we will be looking at is the Chain of Responsibility Pattern. If you ever had a piece of logic that looks like a growing list of conditions, you have probably seen this pattern without naming - [Iterator Design Pattern in Swift](https://livsycode.com/best-practices/iterator-design-pattern-in-swift/) - Greetings, traveler! We use iterators every day without thinking about them. Every for-in loop, every call to map or filter relies on the same mechanism. Swift hides most of the plumbing behind Sequence and IteratorProtocol, so the pattern feels almost invisible. Still, it is worth understanding what actually happens under the hood. Once you see - [Optimizing execution speed with CollectionOfOne in Swift](https://livsycode.com/best-practices/optimizing-execution-speed-with-collectionofone-in-swift/) - Greetings, traveler! There is a type in Swift called CollectionOfOne, which is a collection of one element. Does it sound weird? Don't rush to judge. Check out this example. We can measure the execution time using a benchmark we created in one of the articles. Note By the way, if you'd like to learn more - [Command Design Pattern in Swift](https://livsycode.com/best-practices/command-design-pattern-in-swift/) - Greetings, traveler! At first glance, the Command pattern felt like an academic thing. Something you learn once, then forget. That impression doesn’t survive real projects. Sooner or later, you’ll need to model actions as things: queue them, replay them, store them, undo them, sync them, log them, batch them. That’s what Command is about. What - [PassThroughWindow in iOS26: An Overlay Window That Doesn’t Steal Your Gestures](https://livsycode.com/uikit/passthroughwindow-in-ios26-an-overlay-window-that-doesnt-steal-your-gestures/) - Greetings, traveler! Overlay windows are handy when you need UI that sits above everything else. Think about global toasts, network banners, call-status bars, floating debug panels, or a context menu you want to present independently of your main view hierarchy. The downside is obvious: a UIWindow placed above your app can easily become a gesture - [Agentic coding in Xcode 26.3](https://livsycode.com/blog/agentic-coding-in-xcode-26-3/) - Greetings, traveler! In a recent demo, Apple showed something that feels like a real shift in how development tools work. With Xcode 26.3, coding is no longer just about writing lines of Swift faster. The IDE can now delegate whole engineering tasks to autonomous agents that plan, execute, and iterate on features almost like a - [A WhatsApp-style top banner for iOS using UIWindow and SwiftUI](https://livsycode.com/swiftui/a-whatsapp-style-top-banner-for-ios-using-uiwindow/) - A top banner looks simple until you try to make it reliable across tabs, navigation stacks, SwiftUI hosting, and modal presentations. The approach we’ll consider here solves that problem by addressing it at a higher level: the banner is owned by the UIWindow, and the window pushes the whole app content down using safe-area insets. - [Proxy Design Pattern in Swift](https://livsycode.com/best-practices/proxy-design-pattern-in-swift/) - Greetings, traveler! We continue to analyze Design Patterns, and today, we will focus on the latest Structural Pattern, a Proxy. A Proxy is used in different situations. For instance, you might have a service that you only want to start under specific conditions. In this case, you could use a Proxy to check if the - [How to Avoid Double Updates When Filtering SwiftUI TextField Input](https://livsycode.com/swiftui/how-to-avoid-double-updates-when-filtering-swiftui-textfield-input/) - Greetings, traveler! SwiftUI makes it easy to react to text input. There are two common approaches to handle formatted text input: Use TextField format option Format the string inside onChange and then write the processed value back into the same binding However, using the first option won’t provide you with live text formatting, leaving the - [How to fix 'Extensions must not contain stored properties' error](https://livsycode.com/swift/how-to-fix-extensions-must-not-contain-stored-properties-error/) - Greetings, traveler! This is uncommon, but we may want to store properties within extensions. After doing that, we will immediately find that the compiler does not allow us to do this on the spot. class Object {} extension Object { var property = "" // ❌ Extensions must not contain stored properties }class Object {} - [AI Beyond Coding](https://livsycode.com/blog/ai-beyond-coding/) - Greetings, traveler! Most software developers encounter artificial intelligence through a narrow slice of its applications: large language models, code generation, autocomplete, and what is often called “vibe coding.” This perspective is easy to adopt. These tools are embedded directly into everyday workflows, deliver immediate feedback, and produce visible gains in productivity. For many engineers, AI - [When math draws a hard line for large language models](https://livsycode.com/blog/when-math-draws-a-hard-line-for-large-language-models/) - Greetings, traveler! For the past two years the AI industry has been driven by a simple belief: if models keep growing, today’s limitations will eventually disappear. Better reasoning will emerge. Autonomous agents will become reliable. General intelligence will follow. A recent paper by Vishal Sikka and his son Varin Sikka quietly challenges that assumption — - [iOS 26 adoption: why the "15% panic" was a measurement error](https://livsycode.com/blog/ios-26-adoption-why-the-15-panic-was-a-measurement-error/) - Greetings, traveler! Over the past weeks, a wave of posts claimed that iOS 26 had reached only around 15% of devices. Some headlines framed it as a historic slowdown in Apple’s update cycle. The number spread fast. It also turned out to be wrong. What looked like weak adoption was largely a tracking artifact caused - [Reverse masking in SwiftUI using blend modes](https://livsycode.com/swiftui/reverse-masking-in-swiftui-using-blend-modes/) - Greetings, traveler! SwiftUI gives us mask(_:), which works well when you want to reveal part of a view. What it does not give us is the inverse version — a way to cut shapes out of a view and let whatever sits behind it show through. Let’s walk through a clean and practical way to - [Reaching for UIKit from SwiftUI](https://livsycode.com/swiftui/reaching-for-uikit-from-swiftui/) - Greetings, traveler! SwiftUI is great right up until you need to touch something it doesn’t expose. Maybe you want to tune scroll behavior, read an internal layout value, tweak a gesture recognizer, or integrate with an existing UIKit-based subsystem. In those moments, the temptation is obvious: “If SwiftUI is backed by UIKit anyway, why not - [Container-Based Dependency Injection](https://livsycode.com/best-practices/container-based-dependency-injection/) - Greetings, traveler! Most software systems begin with a limited scope. The number of components is small, interactions are straightforward. As the system evolves, its structure becomes more explicit. Responsibilities are separated, layers emerge, and shared services appear. At this point, attention moves from individual components to the way they are assembled. Dependency Injection emerges as - [Static, Dynamic, and Mergeable Linking in Modular iOS Apps](https://livsycode.com/best-practices/static-dynamic-and-mergeable-linking-in-modular-ios-apps/) - Greetings, traveler! Modularization changes how a project feels day to day. The codebase becomes easier to reason about, feature work becomes more parallel, and dependency boundaries start to matter. At the same time, the build system becomes part of the engineering surface area. Linking strategy is one of the levers that shows up as projects - [Rendering HTML Text in SwiftUI with Custom Link Styling](https://livsycode.com/swiftui/rendering-html-text-in-swiftui-with-custom-link-styling/) - Greetings, traveler! Displaying HTML content in SwiftUI can be surprisingly tricky, especially if you want to go beyond simply rendering raw text. UIKit has long supported rich NSAttributedString rendering with HTML, but SwiftUI still lacks a native way to render HTML while preserving full control over styling. In this post, we'll look at a custom - [Using the Foundation Models Framework for On-Device AI in SwiftUI](https://livsycode.com/swiftui/using-the-foundation-models-framework-for-on-device-ai-in-swiftui/) - Apple introduced the Foundation Models framework, a set of tools enabling developers to integrate on-device AI models into their apps.. Let's implement it then! - [Exploring the @Generable and @Guide Macros in FoundationModels](https://livsycode.com/swiftui/exploring-the-generable-and-guide-macros-in-foundationmodels/) - This article explores the new @Generable and @Guide Swift macros in FoundationModels, demonstrating how they simplify data generation using language models. - [Foundation Models Prompting Guide](https://livsycode.com/best-practices/foundation-models-prompting-guide/) - Greetings, traveler! On-device Foundation Models reward careful prompt design. The model runs with a smaller context window and less headroom for long instructions. When a prompt is vague, overloaded, or padded with filler text, output quality drops fast. Why on-device prompting needs a different playbook Many prompting patterns were popularized around large server models that - [FlyWeight Design Pattern in Swift](https://livsycode.com/best-practices/flyweight-design-pattern-in-swift/) - Greetings, traveler! The Flyweight pattern is a structural design pattern that helps reduce memory usage by sharing common data between multiple objects. It is useful in cases where you need to create a large number of similar objects, and storing the same internal data repeatedly would be wasteful. The key idea Flyweight splits state into - [The Anatomy of Strong Teams in the Age of AI](https://livsycode.com/best-practices/the-anatomy-of-strong-teams-in-the-age-of-ai/) - Greetings, traveler! Large language models have already caused a fundamental shift across multiple domains. Artificial intelligence has changed how we search for information and how we process it. We are still at a very early stage, and many of the current limitations are easy to observe. A lot of behaviors feel unfamiliar, and many people - [Modularity as an Architectural Choice](https://livsycode.com/best-practices/modularity-as-an-architectural-choice/) - Greetings, traveler! Modularity is an architectural approach where a codebase is split into well-defined, independent units with explicit responsibilities and boundaries. Each module exposes a clear public interface and hides its internal details, allowing parts of the system to evolve without tightly coupling everything together. That said, modularity is not a universal requirement. For small - [Handling Non-Breaking Numbers in Dynamic Text](https://livsycode.com/best-practices/handling-non-breaking-numbers-in-dynamic-text/) - Greetings, traveler! Displaying dynamically formatted numbers in user-facing strings is a common requirement in many iOS applications. Price labels, account balances, min/max amounts, and other numeric values often appear as part of longer sentences. While these strings usually render correctly, problems start to appear when a large number doesn't fit on one line. A typical - [Will AI Replace Junior Developers? The Question We’re Asking Wrong](https://livsycode.com/blog/will-ai-replace-junior-developers-the-question-were-asking-wrong/) - Greetings, traveler! Over the past few years, AI has become a natural part of everyday software development. It is no longer an experimental add-on or a novelty tool. It accelerates research, lowers the cost of exploration, and makes prototyping dramatically faster. Tasks that once required hours of documentation reading or trial-and-error can now be approached - [Displaying a SwiftUI View Above a System Alert Using windowLevel](https://livsycode.com/swiftui/displaying-a-swiftui-view-above-a-system-alert/) - Greetings, traveler! In UIKit, every window has a window level. That detail is easy to forget, but it can be useful when you need to present content above a specific system layer. Here, we will walk through a concrete example: how a SwiftUI view can be displayed above a system alert by creating a separate - [Intercepting SwiftUI Sheet Dismissal](https://livsycode.com/swiftui/intercepting-swiftui-sheet-dismissal/) - Greetings, traveler! SwiftUI sheets are great until you need one specific behavior: react when the user tries to dismiss the sheet interactively. You can disable interactive dismissal with .interactiveDismissDisabled(), and you can provide a “Done” button, but there’s still a common UX gap: the user drags the sheet down, expects it to close, and you - [SwiftUI dark mode, light mode, and system theme](https://livsycode.com/swiftui/swiftui-theme-dark-mode-light-mode-and-system-theme/) - Change the theme of the application using SwiftUI: dark mode, light mode, and system theme. We will use the @AppStorage property wrapper to save values. - [Apple’s Misunderstood (2013): A Holiday Ad About Perception](https://livsycode.com/blog/apples-misunderstood-2013-a-holiday-ad-about-perception/) - Greetings, traveler! In December 2013, Apple released a holiday commercial titled Misunderstood. At first glance, it looked like a simple seasonal story about family and Christmas traditions. Over time, however, it became clear that the ad was doing something more subtle — and more lasting. The commercial was later awarded a Primetime Emmy. The story - [Explicit Dependency Injection](https://livsycode.com/best-practices/explicit-dependency-injection/) - Greetings, traveler! When an application is small, dependency injection rarely feels like a problem. Dependencies are simply passed through initializers, and the system remains easy to understand. There is little need for special patterns or tooling, and the code naturally reflects how the application is composed. As the codebase grows, this simplicity often disappears. New - [A Rediscovered 1996 Steve Jobs Interview](https://livsycode.com/blog/a-rediscovered-1996-steve-jobs-interview/) - Greetings, traveler! In an unexpected turn, YouTube surfaced a never-before-seen 1996 interview with Steve Jobs—a recording that had been sitting in obscurity for nearly three decades. The conversation took place right after the release of the first Toy Story, at the moment when Pixar was transitioning from an ambitious graphics research lab into a studio - [Stretchable Header in SwiftUI for Vertical and Horizontal ScrollView](https://livsycode.com/swiftui/stretchable-header-in-swiftui-for-vertical-and-horizontal-scrollview/) - Greetings, traveler! Stretchy headers and elastic overscroll effects have become a familiar part of modern iOS interfaces. They add visual feedback, reinforce the scroll direction, and make content feel more responsive and alive. With newer APIs, the platform now offers a clean solution — and with the right abstraction, the same behavior can be made - [Debugging Swift Code: From print() to LLDB](https://livsycode.com/best-practices/debugging-swift-code-from-print-to-lldb/) - Greetings, traveler! Most iOS projects start with a few print() calls scattered around the codebase. It is the simplest way to see what is going on, and it works surprisingly well for very small problems. The trouble starts when those problems grow, state becomes more complex, and the app needs to be rebuilt again and - [Detecting Device Landscape Orientation in SwiftUI](https://livsycode.com/swiftui/detecting-device-landscape-orientation-in-swiftui/) - Greetings, traveler! When working with adaptive layouts in SwiftUI, one common requirement is to determine whether the device is currently in portrait or landscape mode. While UIKit provides UIDevice.current.orientation, it often produces unreliable results — especially when the device is lying flat. In such cases, values like .faceUp or .faceDown are returned, and UIDeviceOrientation.isLandscape may - [AI-Free — Apple’s New Holiday Ad](https://livsycode.com/blog/ai-free-apples-new-holiday-ad/) - Greetings, traveler! Apple’s latest holiday campaign takes an unexpected direction at a time when AI-driven production dominates almost every corner of the industry. Instead of experimenting with machine-generated visuals or automated animation systems, the team returned to a fully handcrafted approach — and the result stands out precisely because of that restraint. A Handmade Production - [Facade Design Pattern in Swift](https://livsycode.com/best-practices/facade-design-pattern-in-swift/) - Greetings, traveler! So, we gathered again to explore another Design Pattern — the Facade. The Facade pattern is a structural design pattern that defines a simplified, high-level interface to a complex subsystem composed of many classes. Instead of forcing client code to work directly with numerous and often interdependent classes, the facade wraps those classes behind - [SwiftUI Coordinator. Part 2: MVVM Module](https://livsycode.com/swiftui/swiftui-coordinator-part-2-first-mvvm-module/) - This is the second part of the series on implementing the SwiftUI Coordinator. We are building an application that showcases the convenience of this pattern. - [Design Patterns: Basics](https://livsycode.com/best-practices/design-patterns-part-1-basics/) - Greetings, traveler! Design patterns are practical solutions to common software architecture problems in your software development arsenal. Unlike code snippets or libraries, they embody general concepts that address specific issues within your codebase, making them a powerful resource for any developer. Integrating design patterns into your software development process can revolutionize your workflow. These patterns offer pre-built - [Decorator Design Pattern in Swift](https://livsycode.com/best-practices/decorator-design-pattern-in-swift/) - Greetings, traveler! We continue researching Structural Design Patterns as part of our Design Patterns course. It's the turn of the Decorator Design Pattern. We can use this pattern to modify an object's behavior without inheritance. A decorator is a wrapper that alters an object's behavior to provide the desired result in a specific situation. The - [Organizing SwiftUI Views with TabContent and @TabContentBuilder](https://livsycode.com/swiftui/organizing-swiftui-views-with-tabcontent-and-tabcontentbuilder/) - Greetings, traveler! A tab bar is often the backbone of a SwiftUI application. It defines the primary navigation model, sets expectations for the app’s hierarchy, and frames how different sections relate to each other. Yet as a project grows, the tab-bar configuration tends to suffer from the same issue most large SwiftUI views do: it - [Composite Design Pattern in Swift](https://livsycode.com/best-practices/composite-design-pattern-in-swift/) - Greetings, traveler! The Composite design pattern is a powerful structural pattern that helps manage hierarchical data by treating individual objects and compositions uniformly. In Swift development—whether you’re working on UI components, file systems, or domain-specific aggregations—it can significantly simplify client code and foster extensibility. Below is a refined overview of the pattern, practical guidelines, and - [Document Preview Options in SwiftUI](https://livsycode.com/swiftui/document-preview-options-in-swiftui/) - Greetings, traveler! Working with documents is a common requirement in many iOS apps. Whether you're displaying a PDF, showing a Quick Look preview, or handing the file off to the system for deeper interactions, developers today have multiple options available. Each framework offers different capabilities, limitations, and levels of control. This article walks through four - [Accessing UIWindow from SwiftUI](https://livsycode.com/swiftui/accessing-uiwindow-from-swiftui/) - Greetings, traveler! In most SwiftUI-only projects, direct interaction with UIWindow is no longer a daily necessity. SwiftUI abstracts presentation, layout, environment, and view hierarchy in ways that rarely require developers to reach back into UIKit. However, as soon as you introduce multiple scenes, custom overlays, advanced gesture handling, window-level presentation, or programmatic window manipulation (e.g., - [Bridge Design Pattern in Swift](https://livsycode.com/best-practices/bridge-design-pattern-in-swift/) - Greetings, traveler! Let's continue our discussion on Structural Design Patterns. Today, we will explore the Bridge pattern. The Bridge pattern divides a complex system into two hierarchies—abstraction and implementation—that can be developed separately. This allows for more flexibility and easier maintenance of the system. Problem The Bridge pattern addresses a common issue that programmers encounter - [Template Method Design Pattern in Swift](https://livsycode.com/best-practices/template-method-design-pattern-in-swift/) - Greetings, traveler! Let's move on to another Behavioral Design Pattern — the Template Method. This pattern allows us to define the general structure of an algorithm and provides the possibility of overriding some of its steps. You can use this pattern when you want clients to be able to extend only specific steps of an - [SwiftData: Dynamic Query with @State properties](https://livsycode.com/swiftui/swiftdata-dynamic-query-and-fetchdescriptor/) - How to make SwiftData Query dynamic with a descriptor based on @State properties? Let's figure that out. - [Adapter Design Pattern in Swift](https://livsycode.com/best-practices/adapter-design-pattern-in-swift/) - Greetings, traveler! We continue to learn about Design Patterns. Next, we will look at Structural Patterns, starting with the Adapter Pattern. What is the purpose of this pattern? It is used when two different entities need to communicate with each other, but their interfaces are not compatible. The Adapter pattern handles this by bridging the - [How to organize layout with ControlGroup in SwiftUI](https://livsycode.com/swiftui/how-to-organize-layout-with-controlgroup-in-swiftui/) - Greetings, traveler! Have you ever heard about a ControlGroup in SwiftUI? This tool can help create groups of UI components in SwiftUI Views, particularly SwiftUI Menus. Example We can create something like Stepper with this component. struct ControlGroupView: View { var body: some View { ControlGroup { Button { } label: { Image(systemName: "plus") } - [Global actors and Singletons](https://livsycode.com/best-practices/global-actors-and-singletons/) - Singletons are not thread-safe by default. With Swift's new concurrency model, Global Actors provides an alternative method for managing shared resources. - [Singleton Design Pattern in Swift](https://livsycode.com/best-practices/singleton-design-pattern-in-swift/) - Greetings, traveler! Today, I want to discuss the Singleton design pattern as part of our Design Pattern Series. Singleton is one of the most famous and controversial design patterns. It is very popular and even used a lot by Apple, but it is also considered an anti-pattern. But why? First, let me explain Singleton. It - [Localizing Swift Packages in an iOS App](https://livsycode.com/best-practices/localizing-swift-packages-in-an-ios-app/) - Greetings, traveler! Modern iOS architectures often rely on modularization, and Swift Package Manager has become the preferred way to structure reusable components. Each module can include its own resources, including localized strings, images, and other assets. On paper, this allows every feature to be developed and shipped independently. In practice, however, localization inside Swift Packages - [Detecting the Interactive Pop Gesture in SwiftUI](https://livsycode.com/swiftui/detecting-the-interactive-pop-gesture-in-swiftui/) - Greetings, traveler! SwiftUI doesn’t provide a native way to track when the user begins the interactive pop gesture—the swipe from the edge to navigate back. While NavigationStack and NavigationView abstract away UIKit, both still rely on UINavigationController behind the scenes. This opens the door to integrating gesture tracking using UIKit components. This article outlines how - [Prototype Design Pattern in Swift](https://livsycode.com/best-practices/prototype-design-pattern-in-swift/) - Greetings, traveler! We continue our exploration of Creational Design Patterns. Now, it is the turn of the Prototype Design Pattern. When might we need to use it? Consider a scenario where we need to create multiple copies of an object, each with minor differences. How could we approach this? Sure thing, we can create something like this. - [Full-Screen Pop Gesture in UIKit](https://livsycode.com/uikit/full-screen-pop-gesture-in-uikit/) - Greetings, traveler! Many developers have noticed that SwiftUI screens in iOS 26 now support a full-screen pop gesture — allowing users to go back by swiping from anywhere on the screen, not just from the left edge. This small interaction makes navigation feel smoother and more natural, especially on large displays. The good news is - [How to use Debounce in SwiftUI or in Observable classes](https://livsycode.com/swiftui/how-to-use-debounce-in-swiftui-or-in-observable-classes/) - Greetings, traveler! Debouncing is a core technique in responsive UI design — whether you’re delaying API calls while a user types, or limiting frequent updates in real time. For years, Combine’s .debounce has been the go-to solution for Swift developers. But in today’s SwiftUI world, where the Observation framework is replacing @Published and Combine is - [Builder Design Pattern in Swift](https://livsycode.com/best-practices/builder-design-pattern-in-swift/) - Greetings, traveler! Let's continue our fascinating journey into the world of Design Patterns. Today, we unveil the next Creational Design Pattern, the Builder. This technique allows you to construct complex objects piece by piece. Intrigued? Let's delve deeper. Example of usage Let's take a closer look at a live example. Imagine that we need to build - [Smoothly Switching Between Layouts in SwiftUI with AnyLayout](https://livsycode.com/swiftui/smoothly-switching-between-layouts-in-swiftui-with-anylayout/) - Greetings, traveler! When SwiftUI introduced the Layout protocol in iOS 16, it also brought a powerful companion — AnyLayout. This type-erased wrapper allows developers to switch between different layout types without losing state or interrupting animations. It solves a common limitation in earlier SwiftUI versions, where changing from one layout (such as HStack) to another - [Turning a Menu into a Mini Settings Panel in SwiftUI](https://livsycode.com/swiftui/turning-a-menu-into-a-mini-settings-panel-in-swiftui/) - Greetings, traveler! Menus in SwiftUI are often used for quick, one-off commands: select an option, trigger an action, and you’re done. But what if you want a menu to behave less like a simple picker and more like a mini settings panel, where users can toggle multiple options in sequence before committing a final choice? - [Abstract Factory Design Pattern in Swift](https://livsycode.com/best-practices/abstract-factory-design-pattern-in-swift/) - Greetings, traveler! In the previous article, we started to learn about Creational design patterns and discussed the Factory Method. This time, we will look at the Abstract Factory pattern. An Abstract Factory can be helpful in situations where we want to hide the internal details of an object creation behind a public API. This pattern - [Organizing SwiftUI Views with ToolbarContent and @ToolbarContentBuilder](https://livsycode.com/swiftui/organizing-swiftui-views-with-toolbarcontent-and-toolbarcontentbuilder/) - Greetings, traveler! As SwiftUI projects grow, one of the most common challenges developers face is managing increasingly complex view hierarchies. Even a simple screen can quickly expand into dozens of nested modifiers and view declarations. Since Apple lifted the historical limit of ten nested views, it’s become easier than ever to write deeply nested body - [Was Dr. Livesey really a doctor?](https://livsycode.com/blog/was-dr-livesey-really-a-doctor/) - This article is based on V. Tochinov's book Island without Treasures. This investigation may not be relevant to Stevenson's intended meaning, but it is interesting to read. There may also be historical inaccuracies. Spoiler: At that moment in Britain, there was a Jacobite uprising under the leadership of Charles Stuart. Livesey is his trusted person - [Cross-Platform vs AI: The Changing Economics of Mobile Development](https://livsycode.com/blog/cross-platform-vs-ai-the-changing-economics-of-mobile-development/) - Greetings, traveler! The recent release of the Swift SDK for Android is an interesting milestone. It’s a clear signal that Swift is stepping beyond its traditional borders. Today, cross-platform development has never been more accessible - and yet, paradoxically, never more questionable in its long-term value. Because while Swift is crossing platforms, AI is quietly - [Is Apple Using Rust Inside iOS? A Look at the Rumors](https://livsycode.com/blog/is-apple-using-rust-inside-ios-a-look-at-the-rumors/) - Greetings, traveler! Recently, conversations have emerged in the developer community suggesting that Apple might be introducing Rust into the internals of iOS. Some even claim that core system components are being rewritten in Rust, shifting away from Objective-C or Swift. Given Rust’s reputation for memory safety and reliability in systems programming, these rumors are not - [Custom Progress Indicator with SwiftUI Symbol Effects](https://livsycode.com/swiftui/custom-progress-indicator-with-swiftui-symbol-effects/) - Greetings, traveler! Modern iOS apps often rely on subtle motion and clear visual feedback to communicate progress. While SwiftUI includes ProgressView, sometimes you need a lighter, more flexible, and fully stylable indicator that fits seamlessly into your brand’s design system. Let’s walk through how to build a reusable ProgressIndicator component that adapts to different control - [Comparing Two Views with a Gesture-Controlled Slider in SwiftUI](https://livsycode.com/swiftui/comparing-two-views-with-a-gesture-controlled-slider-in-swiftui/) - Greetings, traveler! When you need to visually compare two images, screens, or states of a view, a “before and after” slider is often the most intuitive solution. In this article, we’ll walk through how to build a reusable comparison slider view entirely in SwiftUI — without relying on UIKit or external libraries. Concept Overview The - [Gauge vs ProgressView vs Slider in SwiftUI](https://livsycode.com/swiftui/gauge-vs-progressview-vs-slider-in-swiftui/) - Greetings, traveler! When building data-driven interfaces in SwiftUI, you’ll often need to visualize or control a numeric value. Three native views can serve that purpose — Gauge, ProgressView, and Slider.Although they may look similar at first glance, they differ significantly in intent and interaction. Gauge — Displaying a Value Within a Range Introduced in iOS - [LeetCode Blind 75: Valid Parentheses](https://livsycode.com/dsa/leetcode-blind-75-valid-parentheses/) - Greetings, traveler! One of the most common interview questions from the LeetCode Blind 75 list is Valid Parentheses.It’s short, elegant, and tests a candidate’s understanding of one of the most important data structures — the stack. Problem Overview Given a string containing only the characters '(', ')', '{', '}', '[', and ']',determine whether the input - [LeetCode Blind 75: Valid Anagram](https://livsycode.com/dsa/leetcode-blind-75-valid-anagram/) - Greetings, traveler! Another classic from the LeetCode Blind 75 list — Valid Anagram — is one of those simple problems that interviewers love because it tests how you think about data representation and time complexity trade-offs.Let’s take a look at how to solve it cleanly in Swift. Problem Overview You’re given two strings, s and - [LeetCode Blind 75: Contains Duplicate](https://livsycode.com/dsa/leetcode-blind-75-contains-duplicate/) - Greetings, traveler! When preparing for technical interviews, one of the most common warm-up problems you’ll encounter is “Contains Duplicate” from the LeetCode Blind 75. It’s simple, but it introduces an important concept that appears again and again: using sets to detect uniqueness efficiently. Problem Overview The task is straightforward: Given an integer array nums, return true if any - [Detecting Text Language with NLLanguageRecognizer in Swift](https://livsycode.com/swift/detecting-text-language-with-nllanguagerecognizer-in-swift/) - Greetings, traveler! Language detection is one of those subtle features that can quietly improve user experience—especially in multilingual apps. Whether you’re building a translation tool, a reader app, or adaptive UI that reacts to language, Apple’s NaturalLanguage framework provides a simple and efficient way to determine the dominant language of any text. In this article, - [SwiftUI Toggle with Dynamic Image Overlay](https://livsycode.com/swiftui/swiftui-toggle-with-dynamic-image-overlay/) - Greetings, traveler! While SwiftUI’s built-in Toggle control works perfectly for most cases, sometimes you want something more expressive—something that visually communicates state beyond just color or position. This small exploration shows how to attach a persistent image to a toggle and make it respond naturally to user interaction. The Idea The goal was simple: the - [An Apple Intelligence-Style Glow Effect in SwiftUI](https://livsycode.com/swiftui/an-apple-intelligence-style-glow-effect-in-swiftui/) - Greetings, traveler! Apple’s recent design language introduces a glowing, animated stroke effect that highlights shapes and components in a subtle yet dynamic way. Let’s walk through how to recreate this effect in SwiftUI with reusable extensions. Extending View with Background and Overlay The first step is to make the glow effect easy to apply anywhere. - [How to check if a SwiftUI View is presented modally](https://livsycode.com/swiftui/how-to-check-if-a-swiftui-view-is-presented-modally/) - Greetings, traveler! At times, we may want to establish varying behaviors for the view based on different presentation options. We can do this with minimal effort in SwiftUI. We will use the isPresented EnvironmentValue for this purpose. We can create a property with the Environment property wrapper to read this value. struct DemoView: View { - [LeetCode Blind 75: Two Sum](https://livsycode.com/dsa/leetcode-blind-75-two-sum/) - Greetings, traveler! The Two Sum problem is a classic interview question and a great exercise in algorithmic thinking. The task is simple to state, but it opens the door to multiple solution strategies, each with its own trade-offs. Problem statement:Given an array of integers nums and an integer target, return the indices of the two - [Paging with Peek: Three Ways to Implement Paginated Scroll in SwiftUI](https://livsycode.com/swiftui/paging-with-peek-three-ways-to-implement-paginated-scroll-in-swiftui/) - Creating a horizontally paginated scroll view where adjacent views are partially visible ("peek effect") is a common UI requirement — particularly in carousels or card-based interfaces. Starting with iOS 17, SwiftUI makes this significantly easier. But if your app needs to support earlier iOS versions, alternative approaches are still possible. In this article, we’ll cover - [Forcing a View Reload in SwiftUI](https://livsycode.com/swiftui/forcing-a-view-reload-in-swiftui/) - Greetings, traveler! In SwiftUI, views are declarative and are rebuilt automatically when their underlying state changes. However, there are situations where you may want to force a complete reload of a view. One common technique for achieving this is by using the .id(_:) modifier in combination with a state-driven identifier. Example Implementation Here’s a minimal - [How to prevent screen recording and screenshots in SwiftUI and UIKit](https://livsycode.com/swiftui/how-to-prevent-screen-recording-and-screenshots-in-swiftui-and-uikit/) - Sometimes, we must prevent users from screen recording or taking screenshots. This is not a big deal for both UIKit and SwiftUI. Let's delve into this topic. - [Creating a Bottom Blurred Overlay with a Smooth Gradient in SwiftUI](https://livsycode.com/swiftui/creating-a-bottom-blurred-overlay-with-a-smooth-gradient-in-swiftui/) - Greetings, traveler! When presenting text or controls over images, one of the common challenges is ensuring legibility without completely obscuring the background. A popular approach is to add a blurred overlay that fades in gradually, providing contrast for the foreground elements while preserving the visual context of the background image. In this article, we’ll look - [Exploring Observation in Swift: What Happens with Private Properties](https://livsycode.com/swift/exploring-observation-in-swift-what-happens-with-private-properties/) - Greetings, traveler! Swift’s new Observation framework simplifies the way we track state changes across models. By marking a class with @Observable, we automatically get publisher-like behavior for its properties without manually wiring up @Published. But what happens when the property is private? Does the compiler still generate the boilerplate code for observation? Let’s walk through - [Making Text on Glass Effect Buttons Visible on Any Background](https://livsycode.com/swiftui/making-text-on-glass-effect-buttons-visible-on-any-background/) - Greetings, traveler! At WWDC 2025, Apple introduced a new UI design philosophy, highlighted by the glass effect. This approach delivers a visually striking aesthetic, moving beyond traditional button backgrounds to create an immersive user experience. The glass effect, characterized by its translucent and reflective qualities, adds depth and sophistication to iOS interfaces. However, the adoption - [Glass Options in iOS 26: Clear vs Regular (Frosted Glass)](https://livsycode.com/swiftui/glass-options-in-ios-26-clear-vs-regular-frosted-glass/) - Greetings, traveler! With the introduction of the new liquid glass interface paradigm in iOS 26, Apple has taken another step toward blending visual fidelity with spatial depth. However, this change has raised a number of concerns — not just among developers and designers, but among users as well. Chief among them is a familiar question: - [Building a Native Link Preview in SwiftUI](https://livsycode.com/swiftui/building-a-native-link-preview-in-swiftui/) - Greetings, traveler! Modern applications often enhance user experience by providing rich previews for shared links. These previews typically include an image, title, and domain, giving users context before they decide to open a URL. In this article, we’ll explore how to build a native link preview component in SwiftUI using built-in frameworks like LinkPresentation, SwiftUI, - [A Delayable Progress Indicator in SwiftUI](https://livsycode.com/swiftui/a-delayable-progress-indicator-in-swiftui/) - Greetings, traveler! One of the common UX issues in iOS applications is the appearance of loading indicators for operations that complete almost instantly. When the indicator briefly appears and disappears, it creates a “flicker” effect which users perceive as visual noise. A better approach is to display the indicator only if the operation takes longer - [When onAppear and task Are Not Triggered in SwiftUI](https://livsycode.com/swiftui/when-onappear-and-task-are-not-triggered-in-swiftui/) - Greetings, traveler! In SwiftUI, both .onAppear and .task are commonly used to perform actions when a view becomes visible. In most cases they work exactly as expected — the moment a view appears in the hierarchy, the modifier is triggered. However, there are a couple of situations where these callbacks are not executed, even though - [When Importing Foundation Changes Swift’s Behavior](https://livsycode.com/swift/when-importing-foundation-changes-swifts-behavior/) - Greetings, traveler! Swift is often described as a modern language with its own standard library, while Foundation comes from the Objective-C era and provides a wide set of APIs for working with strings, collections, dates, and more. What’s less obvious is that importing Foundation can actually change the behavior of methods you might think are - [Opening a Specific Tab from a Notification in SwiftUI](https://livsycode.com/swiftui/opening-a-specific-tab-from-a-notification-in-swiftui/) - Greetings, traveler! Handling app navigation triggered by system events like local notifications is a common requirement. In SwiftUI, achieving this in a clean and reliable way requires a slightly different approach compared to UIKit. This article presents a minimal solution for switching to a specific tab in a TabView when a user taps on a - [Injecting Colors into the SwiftUI View Hierarchy](https://livsycode.com/swiftui/injecting-style-hierarchy/) - Greetings, traveler! In SwiftUI, one of the more elegant patterns for customizing visuals is style injection. Rather than passing explicit colors or style parameters down the view tree manually, SwiftUI allows us to inject style information at a higher level using modifiers like .foregroundStyle(), .backgroundStyle(), and .tint(). These injected styles can then be consumed by - [ConcentricRectangle and Corner Radius Consistency](https://livsycode.com/swiftui/concentricrectangle-and-corner-radius-consistency/) - Greetings, traveler! In interface design, consistent corner radii help reinforce structure and spatial relationships. When one container nests within another, the inner view’s corner radius should visually correspond to the outer radius minus the padding. This ratio-based adjustment ensures that the nested shape appears as part of the same rounded surface rather than a separate - [Backporting onChange(of:old:new:) for iOS 16](https://livsycode.com/swiftui/backporting-onchangeofoldnew-for-ios-16/) - Starting with iOS 17, SwiftUI introduced a new overload of the onChange(of:) modifier. This version includes both the old and new values in the closure, making many state-driven UI updates cleaner and more reliable. However, when targeting iOS 16 and earlier, this version of onChange is unavailable. To provide consistent behavior across OS versions, it's - [How to handle two types of server responses to a single request in Swift](https://livsycode.com/swift/how-to-handle-two-types-of-server-responses-to-a-single-request-in-swift/) - Let's look at this example and see how we can find a solution to escape the situation where we have a single request but multiple cases of server response. - [Type-safe NotificationCenter in Swift 6.2](https://livsycode.com/swiftui/type-safe-notificationcenter-in-swift-6-2/) - Greetings, traveler! In modern Swift, broadcast messaging via NotificationCenter has always been flexible but often error-prone. It relies on loosely-typed userInfo dictionaries and string-based keys, creating risks of typos, type mismatches, and silent failures. Swift 6.2 introduces a new, structured solution: typed messages using the NotificationCenter.Message protocol family. This approach provides compile-time safety, better clarity, - [Adding Subtitles to Navigation Bar in SwiftUI](https://livsycode.com/swiftui/adding-subtitles-to-navigation-bars/) - Greetings, traveler! Starting with iOS 26, SwiftUI introduces a way to add subtitles to navigation bar titles. It’s done through a new view modifier:.navigationSubtitle(_:). This modifier lets you add a secondary line of text under the main navigation title, using the same NavigationStack or NavigationSplitView structure you already use. How It Works The navigationSubtitle(_:) modifier - [How to use @Animatable macro in SwiftUI](https://livsycode.com/swiftui/how-to-use-animatable-macro-in-swiftui/) - The new @Animatable macro marks a Shape as animatable. It automatically handles interpolation for all properties that can be animated—such as numbers, angles, and sizes—without requiring any manual conformance or calculations. - [A Native SwiftUI WebView](https://livsycode.com/swiftui/a-native-swiftui-webview/) - Greetings, traveler! For years, displaying web content in SwiftUI meant falling back to WKWebView from UIKit. It worked, but it always felt like a workaround. Starting with iOS 18.4, Apple added a native WebView for SwiftUI. No more UIViewRepresentable, no more bridging. Just import WebKit and SwiftUI, and you are good to go. How It - [How to use AttributedString with TextEditor in SwiftUI](https://livsycode.com/swiftui/how-to-use-attributedstring-with-texteditor-in-swiftui/) - With the release of iOS 26, Apple introduced support for AttributedString as a binding for TextEditor, along with a new formatting menu for selected text. - [Applying the backgroundExtensionEffect Modifier in SwiftUI](https://livsycode.com/swiftui/applying-the-backgroundextensioneffect-modifier-in-swiftui/) - Introduced in iOS 26, the backgroundExtensionEffect modifier in SwiftUI enables developers to extend a view’s visual content beyond its safe area by creating mirrored copies with a blur effect. - [Using the scrollEdgeEffectStyle Modifier in SwiftUI](https://livsycode.com/swiftui/using-the-scrolledgeeffectstyle-modifier-in-swiftui/) - Apple’s iOS 26 introduces the scrollEdgeEffectStyle modifier in SwiftUI, which allows developers to customize the appearance of content transitions at the edges of a scroll view. - [How to use tabBarMinimizeBehavior in SwiftUI](https://livsycode.com/swiftui/how-to-use-tabbarminimizebehavior-in-swiftui/) - Apple’s iOS 26 introduces the tabBarMinimizeBehavior API in SwiftUI, allowing developers to control how a tab bar behaves during user interactions. - [Implementing the glassEffect in SwiftUI](https://livsycode.com/swiftui/implementing-the-glasseffect-in-swiftui/) - Apple's iOS 26 introduces a new visual style with the glassEffect modifier in SwiftUI, enabling developers to apply a translucent, glass-like appearance to views. - [Numeric TextField in SwiftUI](https://livsycode.com/swiftui/numeric-textfield-in-swiftui/) - Greetings, traveler! When working with numeric text fields in SwiftUI, setting .keyboardType(.numberPad) or .decimalPad is often a first step toward guiding user input. However, these configurations alone do not guarantee clean numeric input. Users can still paste non-numeric values, use external keyboards, or encounter full keyboards on iPads. To ensure consistent and valid input, the - [SwiftUI custom TextField. Part 4: Input validation](https://livsycode.com/swiftui/select-swiftui-custom-textfield-part-4-input-validation/) - This is the fourth part of a series of articles about creating a custom SwiftUI TextField. Today, we will discuss input validation for a better user experience. - [How to Fix toolbar Issues in SwiftUI When Using the Keyboard](https://livsycode.com/swiftui/how-to-fix-toolbar-issues-in-swiftui-when-using-the-keyboard/) - According to reports from multiple developers, .toolbar content can fail to appear when the keyboard is shown. In this post, we will consider a way to fix it. - [SwiftUI custom TextField. Part 1: Basics](https://livsycode.com/swiftui/swiftui-textfield-with-uiviewrepresentable/) - A flexible SwiftUI TextField with customization, masking, and text validation. This is the first article where we will discuss the basics. - [SwiftUI custom TextField. Part 5: Input mask](https://livsycode.com/swiftui/swiftui-custom-textfield-part-5-input-mask/) - This is the last part of a series of articles about creating a custom SwiftUI TextField. Today, we will discuss text field input masking. - [SwiftUI custom TextField. Part 3: InputAccessoryView](https://livsycode.com/swiftui/swiftui-custom-textfield-part-3-inputaccessoryview/) - A Custom SwiftUI TextField with flexible customization. In this part, we will add a toolbar above the keyboard using inputAccessoryView. - [SwiftUI custom TextField. Part 2: Customization](https://livsycode.com/swiftui/swiftui-custom-textfield-part-2-customization/) - A Custom SwiftUI TextField with flexible customization, validation, and masking. In this part, we will explore customization in more detail. - [How to toggle Secure Input in SwiftUI TextField](https://livsycode.com/swiftui/how-to-toggle-secure-input-in-swiftui-textfield/) - In UIKit, we have a isSecureTextEntry property. But there is no native way to toggle the secure input state of a text field, but we create a custom wrapper to achieve this behaviour. - [Understanding @resultBuilder in Swift: Beyond SwiftUI](https://livsycode.com/swiftui/understanding-resultbuilder-in-swift-beyond-swiftui/) - Swift’s @resultBuilder attribute is a powerful feature that simplifies the creation of domain-specific languages (DSLs) within Swift, enabling expressive and concise declarative code. - [Exploring withExtendedLifetime in Swift](https://livsycode.com/swift/exploring-withextendedlifetime-in-swift/) - Greetings, traveler! Swift’s Automatic Reference Counting (ARC) is a powerful mechanism for managing memory, automatically freeing objects when they are no longer referenced. However, there are rare cases where ARC’s optimizations can lead to objects being deallocated earlier than expected, causing subtle bugs, especially in optimized builds. To address this, Swift provides a utility called - [How to use withoutActuallyEscaping](https://livsycode.com/swift/how-to-use-withoutactuallyescaping/) - Greetings, traveler! Closures in Swift are powerful tools that can be either escaping or non-escaping. By default, closures passed as function parameters are non-escaping, meaning they are not stored or used after the function completes. However, some APIs require escaping closures, marked with @escaping, which can be stored or executed later. This article explores withoutActuallyEscaping, - [Conditional View Modifiers in SwiftUI: Convenience and Caveats](https://livsycode.com/swiftui/conditional-view-modifiers-in-swiftui-convenience-and-caveats/) - Greetings, traveler! SwiftUI's declarative syntax makes it easy to build dynamic user interfaces, but sometimes you need to apply view modifiers conditionally based on specific states or conditions. One approach to achieve this is through a custom conditional view modifier, which can streamline your code and improve readability. However, while this technique is powerful, it - [Three Practical Tools for Managing References and Detecting Memory Leaks in Swift](https://livsycode.com/best-practices/three-practical-tools-for-managing-references-and-detecting-memory-leaks-in-swift/) - Whether you’re maintaining a list of delegates or debugging a stubborn retain cycle, tools for managing references and monitoring memory can save hours of frustration. In this article, I’ll walk through three lightweight but powerful building blocks you can introduce into your Swift toolkit: Tools for working with collections of weak objects It's thread-safe versions - [Codable Dictionary with enum as key](https://livsycode.com/swift/codable-dictionary-with-enum-as-key-with-codingkeyrepresentable/) - How to properly encode a Dictionary with an enum as a key using the CodingKeyRepresentable protocol. - [How to access UIHostingController from a SwiftUI View](https://livsycode.com/swiftui/how-to-access-uihostingcontroller-from-a-swiftui-view/) - Greetings, traveler! When working with SwiftUI, you often need to bridge UIKit and SwiftUI components. One common requirement is to access the underlying UIHostingController from within a SwiftUI view. This can be useful when you need to perform UIKit-specific actions such as navigation, presenting alerts, or interacting with UIKit lifecycle events. In this article, we'll - [Leveraging Enums for Flexible Button Styling in SwiftUI](https://livsycode.com/swiftui/leveraging-enums-for-flexible-button-styling-in-swiftui/) - Greetings, traveler! Enums in Swift are a powerful tool for defining a set of related values in a type-safe way. Beyond their basic use for representing fixed options, enums can serve as a foundation for more complex logic, enabling clean and maintainable code in iOS applications. In this article, we’ll explore how enums can be - [Exploring the take() method for Optionals](https://livsycode.com/best-practices/exploring-the-take-method-for-optionals/) - With the take() method, you can extract the value from an Optional, return it if it exists, and set it to nil afterward. - [Simplifying Focus Management in SwiftUI with a Custom ViewModifier](https://livsycode.com/swift/simplifying-focus-management-in-swiftui-with-a-custom-viewmodifier/) - Greetings, traveler! SwiftUI's @FocusState property wrapper is a powerful tool for managing focus in your app's UI, but it comes with some limitations that can make it cumbersome to use in certain scenarios. For instance, it doesn't integrate seamlessly with @Binding, can't be used in view models, is tricky to pass between views, and behaves - [Modular Form Validation in SwiftUI](https://livsycode.com/swiftui/modular-form-validation-in-swiftui/) - Greetings, traveler! When working with forms in SwiftUI, validation logic can quickly become tangled—especially as the number of fields grows. In this article, I’ll walk you through a demo implementation that focuses on clean, modular validation for text fields, using a flexible architecture that scales well. Although the code also supports debounced validation and custom - [InlineArray – A Fixed-Size Arrays in Swift](https://livsycode.com/swift/inlinearray-a-fixed-size-arrays-in-swift/) - Greetings, traveler! Swift 6.2 introduces a powerful new data structure: InlineArray.If you've ever needed an array with a fixed size, optimized for performance, but found tuples too clunky and standard arrays too flexible — this feature is for you. Think of InlineArray as the best of both worlds: Like tuples, it has a predefined size - [Weak let for Safer Immutable References](https://livsycode.com/swift/weak-let-for-safer-immutable-references/) - Greetings, traveler! Swift 6.2 brings a subtle but powerful language enhancement: you can now declare properties using weak let. This complements the existing weak var, offering a new way to create immutable yet non-owning references to class instances. At first glance, weak let might seem like a contradiction — how can something be both weak - [Observing Value Changes with Observations in Swift 6.2](https://livsycode.com/swift/observing-value-changes-with-observations-in-swift-6-2/) - How to observe changes outside of SwiftUI View? Swift 6.2 introduces a new API for tracking changes in @Observable data: the Observations type. - [Making String Interpolation Smarter in Swift 6.2: Default Values for Optionals](https://livsycode.com/swift/making-string-interpolation-smarter-in-swift-6-2-default-values-for-optionals/) - Swift 6.2 introduces a subtle but powerful enhancement through SE-0477: the ability to specify default values directly within string interpolations for optionals. It’s one of those changes that may look trivial at first glance — but under the surface, it solves a long-standing pain point and brings elegance to previously clunky code. The Basic Idea - [Raw Identifiers in Swift 6.2](https://livsycode.com/swift/raw-identifiers-in-swift-6-2/) - Greetings, traveler! Swift 6.2 brings a subtle but powerful change to the language with SE-0451, allowing developers to use almost any characters in identifier names—by wrapping them in backticks (`). This makes your code more expressive, more readable, and in many cases, just more natural. You can now write functions like this: func `something special`() - [A Pull-Cord Theme Switcher in SwiftUI](https://livsycode.com/swiftui/a-pull-cord-theme-switcher-in-swiftui/) - Greetings, traveler! When it comes to great UX in mobile apps, even small details can create moments of delight. In this post, I’ll show you how to build a unique, tactile UI element in SwiftUI — a pull-cord switch, inspired by the kind used to turn lights on and off. It’s a fun and physical-feeling - [MFMailComposeViewController in SwiftUI](https://livsycode.com/swiftui/mfmailcomposeviewcontroller-in-swiftui/) - In iOS development, sending emails directly from your app can enhance user interaction by providing a seamless experience for sharing information or contacting support. In this tutorial, we'll explore how to integrate MFMailComposeViewController with SwiftUI to allow users to compose and send emails from within your app. SwiftUI View We will create a SwiftUI view - [Custom transition for fullScreenCover in SwiftUI](https://livsycode.com/swiftui/custom-transition-for-fullscreencover-in-swiftui/) - Add a custom transition to full-screen covers with a custom view modifier. Experiment with different transitions, such as .scale, move(edge:), or .asymmetric. - [Underscore attributes: @_implicitSelfCapture](https://livsycode.com/swift/swift-underscore-attributes-_implicitselfcapture/) - Did you notice that using Task does not require explicit use of self? That's because the Task's closure is marked with the @_implicitSelfCapture attribute. - [How to use Hierarchical Colors in SwiftUI](https://livsycode.com/swiftui/how-to-use-hierarchical-colors-in-swiftui/) - Greetings, traveler! In SwiftUI, colors can be organized hierarchically to create a consistent and scalable color system. This hierarchical system typically includes primary, secondary, tertiary, quaternary, and quinary colors. Each subsequent color will be less opaque. You can use any color you want, including custom presets, accent color, and system colors. Let's check out an - [How to display byte counts in Swift](https://livsycode.com/swiftui/how-to-dysplay-byte-counts-in-swift/) - We will use ByteCountFormatter and ByteCountFormatStyle to do this. Let's check out some examples. - [Formatting Numbers into Words in Swift](https://livsycode.com/swiftui/formatting-numbers-into-words-in-swift/) - This article will explore how to convert numbers to their word equivalents using NumberFormatter easily. - [How to use Spacer with ScrollView in SwiftUI](https://livsycode.com/swiftui/how-to-use-spacer-with-scrollview-in-swiftui/) - How can we fix the problem when Spacer doesn't work with ScrollView? - [How to change the order of Calendar weekdaySymbols](https://livsycode.com/swift/how-to-change-the-order-of-calendar-weekdaysymbols/) - Greetings, traveler! Today, I want to talk about weekday order in Swift. Sometimes, we need to compose weekdays, for example, if we are creating a calendar with weekday representation. Swift offers a Calendar.weekdaySymbols—an instance property representing a weekday list. Let's use it then. let calendar = Calendar.current let symbols = Calendar .current .weekdaySymbols symbols // - [Atomic properties and collections in Swift](https://livsycode.com/swift/atomic-properties-and-collections-in-swift/) - Swift does not have a public API for marking properties as atomic ones, but we can make one ourselves. However, this approach may not be without its challenges. - [Mutex in Swift 6 and Synchronization](https://livsycode.com/swift/mutex-in-swift-6-and-synchronization/) - Greetings, traveler! Today, we will discuss thread safety once again. Earlier, we discussed this with examples related to singletons and global actors, as well as the creation of custom structures and classes for atomic operations. This article will discuss a new way to handle atomic operations with a new Apple framework called Synchronization, which is - [How to schedule local notifications for weekdays and timestamps](https://livsycode.com/swift/how-to-schedule-local-notifications-for-weekdays-and-time-points/) - Greetings, traveler! Notifications are a popular tool for communicating with users. They can be local or remote. Remote notifications can be handled via external services like Firebase or Supabase, while local ones can be created and scheduled inside the app. Let's take a closer look at how we can do this. Notification Service Imagine we - [Attributed text with Text view interpolation in SwiftUI](https://livsycode.com/swiftui/attributed-text-with-text-view-interpolation-in-swiftui/) - Did you know you can use a Text view to create attributed text through string interpolation? - [Global actors in Swift](https://livsycode.com/swift/global-actors-in-swift/) - Greetings, traveler! Sometimes, you may need to execute a portion of your code within a specific actor, even if that code doesn't belong to that actor. Here, the Global Actors are coming to the rescue. MainActor For example, you can use the @MainActor attribute to run your code on the main thread. Let's delve into - [How to display an icon with a title using the Label in SwiftUI](https://livsycode.com/swiftui/how-to-display-an-icon-with-a-title-with-label-in-swiftui/) - Greetings, traveler! SwiftUI provides a straightforward way to display text and icons together using the Label view. You can use it with SF Symbols: struct ContentView: View { var body: some View { Label("Favorites", systemImage: "star") } } Or with custom Images struct ContentView: View { var body: some View { Label("Favorites", image: "star") } - [How to format date in SwiftUI](https://livsycode.com/swiftui/how-to-format-date-in-swiftui/) - Greetings, traveler! Displaying dates in SwiftUI has become remarkably straightforward, reducing reliance on DateFormatter for basic date display. This API will use the current locale, so examples can produce different results. So, let's check out the code. import SwiftUI struct ContentView: View { var body: some View { // 10.12.2024, 20:54 Text(Date.now.formatted()) // 10.12.2024 Text(Date.now.formatted(date: - [How to create a binding to an environment object in SwiftUI](https://livsycode.com/swiftui/how-to-create-a-binding-to-a-property-of-an-environment-object-in-swiftui/) - Greetings, traveler! Since Apple introduced the Observation framework in iOS 17, life has become easier, and code has become faster. With the new Observation framework, you can migrate from the ObservableObject protocol to the Observable macro and from the EnviromentObject to the Enviroment. With Observable macro, all properties become observable by default. But what if - [How to render a SwiftUI view to an image or a PDF](https://livsycode.com/swiftui/how-to-render-a-swiftui-view-to-an-image-or-a-pdf/) - Greetings, traveler! SwiftUI offers a great tool to render your views into images or PDFs. I am talking about ImageRenderer. Image Let's take a closer look at some examples then. Frist, let's render an image. Create an extension for View to use ImageRenerer. Here, we should provide a display scale. To this, we can use - [How to add padding between a TextField and the keyboard in SwiftUI](https://livsycode.com/swiftui/how-to-add-padding-between-a-textfield-and-the-keyboard-in-swiftui/) - SwiftUI has a keyboard avoidance mechanism, but what if we want to add some extra space below the TextField? Check out how we can do this. - [How to use property wrappers with @Observable Macro](https://livsycode.com/swift/how-to-use-property-wrappers-with-observable-macro/) - Property wrapper cannot be applied to a computed property. We can avoid this error in the class, which was marked with @Observable Macro when using property wrappers. - [File System CRUD operations manager](https://livsycode.com/best-practices/file-system-crud-operations-manager/) - If your app frequently uses the File System, you may want to create a universal tool to perform CRUD operations. So, let's do this. - [SwiftUI Custom Progress Bar with masking](https://livsycode.com/swiftui/swiftui-custom-progress-bar-with-masking/) - We can use GeometryReader to create a custom progress bar with masking and change the text color with this mask. - [SwiftUI Spoiler View with particles](https://livsycode.com/swiftui/swiftui-spoiler-view-with-particles/) - CAEmitterLayer is a valuable tool for creating particle effects like smoke, fire, snow, etc. Today, we will use it to make a spoiler view with particles. - [Underscore attributes: @_implements](https://livsycode.com/swift/underscore-attributes-_implements/) - This attribute indicates that a function with one name satisfies a protocol requirement with a different name. Let's check out how to use it. - [Underscore attributes: @_disfavoredOverload](https://livsycode.com/swift/underscore-attributes-_disfavoredoverload/) - This attribute marks an overload that the type checker should try to avoid using. And does Swift have some hidden principles while executing code? - [Underscore attributes: @_marker](https://livsycode.com/swift/underscore-attributes-_marker/) - Marker protocols are used to mark entities without providing any requirements. But did you know Swift has a specific underscore attribute for such protocols? - [How to check Internet connection in Swift](https://livsycode.com/swift/how-to-check-internet-connection-in-swift/) - Greetings, traveler! If your app is highly bound to a network connection, informing the user if the connection is lost will be a nice decision. You can do it via Apple's framework called Network. To monitor and react to network changes, you can use the NWPathMonitor class. For convenience, we will create a wrapper for - [Underscore attributes: @_exported](https://livsycode.com/swift/underscore-attributes-_exported/) - Working with modular architecture, we need to make many imports at the beginning of the file. However, the @_exported attribute can reduce the number of imports. - [SwiftUI Week Calendar View. #1: Introduction](https://livsycode.com/swiftui/swiftui-week-calendar-view-1-introduction/) - Infinite SwiftUI Week Calendar View with flexible customization tutorial. Source code provided. - [SwiftUI Week Calendar View. #5: WeekCalendarView](https://livsycode.com/swiftui/swiftui-week-calendar-view-5-weekcalendarview/) - Greetings, traveler! We continue our series about SwiftUI Week Calendar View. This is the fifth part, where we will create the WeekCalendarView. The title of this article looks a bit weird, but it marks that this article is a key one. If you just want to check out the complete source code, here it is. As - [SwiftUI Week Calendar View. #4: WeekView](https://livsycode.com/swiftui/swiftui-week-calendar-view-4-weekview/) - Infinite SwiftUI Week Calendar View with flexible customization tutorial. Source code provided. - [SwiftUI Week Calendar View. #3: Provider](https://livsycode.com/swiftui/swiftui-week-calendar-view-3-provider/) - Infinite SwiftUI Week Calendar View with flexible customization tutorial. Source code provided. - [SwiftUI Week Calendar View. #2: Models](https://livsycode.com/swiftui/swiftui-week-calendar-view-2-models/) - Infinite SwiftUI Week Calendar View with flexible customization tutorial. Source code provided. - [How to track changes in an Observable class outside of SwiftUI views](https://livsycode.com/swiftui/how-to-track-changes-in-an-observable-class-outside-of-swiftui-views/) - Greetings, traveler! Apple introduced the Observation framework during WWDC 2023 to replace ObservableObject via the new Observable macro. This framework allows us to redraw SwiftUI views after applying changes to an Observable class. But what if we want to track these changes outside of SwiftUI views? There is a way to do this. Looking ahead, - [OptionSet vs Enum](https://livsycode.com/best-practices/optionset-vs-enum/) - Greetings, traveler! Have you ever used the OptionSet protocol? It doesn't look like an everyday tool, but it can be helpful in specific cases. What is an OptionSet? This type presents a mathematical set interface to a bit set. This is a bitset type, where every bit represents an option. If you are familiar with - [Binding vs Bindable vs State](https://livsycode.com/swiftui/binding-vs-bindable-vs-state/) - Greetings, traveler! Since we have discussed binding, let's clarify Swift's different options. iOS 17 and the new Observation framework gave us some new tools to consider, which widened our arsenal. So, let's take a closer look at all of them once again. State Utilize the @State property wrapper to manage a single source of truth - [Pretty printed JSON Data](https://livsycode.com/best-practices/pretty-printed-json-data/) - Greetings, traveler! Have you ever tried printing out server response data in the console? I guess you do. Let's consider an example. let json = """ { "id": "22", "title": "livsycode", "info": { "info1": { "status": "ready" }, "info2": { "time": "22:11" }, } } """ let jsonData = json.data(using: .utf8) ?? .init() To check - [Dealing with measurement units in Swift](https://livsycode.com/swift/dealing-with-measurement-units-in-swift/) - Greetings, traveler! Have you ever encountered measurement units in your app? Sometimes, we don't need to overthink this topic. But sometimes, we need to manage measurement units in more detail. For this occasion, Apple has a specific API. Measurement — a numeric quantity labeled with a unit of measure, supporting unit conversion and unit-aware calculations. - [How to create mock arrays with Array(repeating:count:)](https://livsycode.com/swift/how-to-create-mock-arrays-with-arrayrepeatingcount/) - Greetings, traveler! Sometimes, we need to create some mock data. It looks tricky at first glance when we talk about arrays with extensive data. However, there is an API in Swift that can help us create such an array in a single line of code. Check out this example: let stringArray = [String](repeating: "", count: - [Consume operator in Swift](https://livsycode.com/best-practices/how-to-use-consume-operator/) - Greetings, traveler! Imagine a scenario where you have to pass a model through multiple functions. Consider this example: struct Model { let name: String } func firstMethod() { let model = Model(name: "ModelName") secondMethod(model: model) } func secondMethod(model: Model) { print(model.name) } firstMethod() The issue is that the initial model created in the first function - [Blur transition animation with blurReplace in SwiftUI](https://livsycode.com/swiftui/blur-transition-animation-with-blurreplace-in-swiftui/) - Greetings, traveler! Smooth transitions always enhance the user experience. iOS 17 introduces a new animation called blurReplace that can be combined with others to create even more beautiful effects. Check out this example. We have a ScrollView, where we can add and remove items. struct SwiftUIView: View { @State private var array: [Int] = [] - [Detect when your app is sent to the background or foreground in SwiftUI](https://livsycode.com/swiftui/detect-when-our-app-is-sent-to-the-background-or-foreground-in-swiftui/) - Greetings, traveler! We can change our app's behavior based on its current state. We can do this in UIKit and SwiftUI. This article will describe a SwiftUI way of app phase monitoring. Note By the way, if you want to learn how to do this via UIKit, you can check out this article. UIApplication We - [Detect when your app is sent to the background in UIKit](https://livsycode.com/uikit/detect-when-our-app-is-sent-to-the-background-in-swift-and-uikit/) - Greetings, traveler! Sometimes, we must change an application's behavior based on its current state. Let's examine how to do this in UIKit. Note By the way, if you want to learn how to do it in SwiftUI, you can check out this article. The AppDelegate.swift file contains a suitable method called applicationWillResignActive(). We can use - [Progress Bar with image pattern mask in SwiftUI](https://livsycode.com/swiftui/progress-bar-with-image-pattern-mask-in-swiftui/) - Greetings, traveler! Expanding on the previous article, I want to demonstrate using image patterns to create a custom progress bar in SwiftUI. There is an easy way to do this. Following this tutorial, create an Image with a resizable() modifier. Image(uiImage: image) .resizable(resizingMode: .tile) .frame(height: imageHeight) You can also resize a UIKit UIImage to use - [How to create pattern with image in SwiftUI and UIKit](https://livsycode.com/swiftui/how-to-create-pattern-with-image-in-swiftui-and-uikit/) - Greetings, traveler! If you need to create a pattern using an image, you can do this with simple actions in UIKit and SwiftUI. UIKit To create a pattern-like background for UIView, you can convert any image into UIColor. Check out this code: let image = UIImage(named: "myImage") ?? .init() let view = UIView() view.backgroundColor = - [Type '()' cannot conform to 'View' or how to use print() inside SwiftUI View](https://livsycode.com/swiftui/type-cannot-conform-to-view-or-how-to-use-print-inside-swiftui-view/) - Greetings, traveler! Most of us sometimes use print for debugging. But if we place this method inside a SwiftUI View, we will achieve this error: Type '()' cannot conform to 'View' There are several ways to handle this issue. print() Just assign this method as the constant's value. It will be called during every render - [Should we use the weak self with DispatchQueue?](https://livsycode.com/swift/should-we-use-the-weak-self-with-dispatchqueue-main-async/) - Greetings, traveler! We often use DispatchQueue to perform tasks on a specific thread serially or concurrently. Expecting different code bases, we can notice that some developers capture weak references inside the DispatchQueue closure, and some developers don't do that. Let's figure out who is right. We can ask someone who didn't capture weak references directly. - [The right way to compare strings in Swift](https://livsycode.com/best-practices/the-right-way-to-compare-strings-in-swift/) - Greetings, traveler! Today, we will talk about string comparison. There is a prominent method to do that. Check out this example: let string1 = "Livsy Code" let string2 = "Livsy Code" string1 == string2 // true However, in some cases, we must prioritize safety in our string comparisons. Consider this example: struct User { let - [How to use PersonNameComponents Formatter](https://livsycode.com/best-practices/how-to-use-personnamecomponentsformatter/) - Greetings, traveler! There are a lot of apps where a user name is displayed. To display a person's name, we can do something like this: struct User { let givenName: String let familyName: String } let user = User(givenName: "Artem", familyName: "Mirzabekian") let labelText = "\(user.givenName) \(user.familyName)" // Artem Mirzabekian If your user is from - [How to measure execution speed in Swift](https://livsycode.com/swift/how-to-measure-execution-speed-in-swift/) - Sometimes, it would be helpful to know how fast our code is executed. The CFAbsoluteTimeGetCurrent() makes this very simple. - [Swift Timer and retain cycles](https://livsycode.com/swift/swift-timer-and-retain-cycles/) - Greetings, traveler! Swift Timer is a popular API. Most developers have experience with it. However, this class holds hidden dangers that may take time to be noticeable. I am talking about retaining cycles, which a Timer can cause. Check out this code. import UIKit class ViewController: UIViewController { private var timer: Timer? override func viewDidLoad() - [SwiftUI isUserInteractionEnabled alternatives: disabled vs allowsHitTesting](https://livsycode.com/swift/swiftui-isuserinteractionenabled-alternatives-disabled-vs-allowshittesting/) - Sometimes, it is necessary to disable the ability to interact with a view using gestures. Let's look at how to disable taps for a view in SwiftUI. - [How to implement ChatGPT in Swift](https://livsycode.com/swift/how-to-implement-chatgpt-in-swift/) - OpenAI provides a convenient API for developers to integrate their chatbot functionality into iOS applications. - [The Swifty way to swizzle: @_dynamicReplacement](https://livsycode.com/swift/the-swifty-way-to-swizzle-_dynamicreplacement/) - Greetings, traveler! In the previous article, we considered a variant of swizzling based on Objective-C methods. However, there is a more modern way to do this, taking advantage of the Swift language: type safety and simplicity. For an entity to be dynamically replaced, it must be marked with the dynamic keyword. Let's look at an - [How to find similar words with an NLEmbedding](https://livsycode.com/swift/how-to-find-similar-words-with-an-nlembedding/) - Greetings, traveler! Imagine that you want to create a search function that works for the specific word and words related to the same context. Apple has a handy tool for this. Unfortunately, it does not work with all languages at the time of writing this article. So, we will check out the example in English. - [Swizzling in Swift with the UIViewController example](https://livsycode.com/swift/swizzling-in-swift-with-the-uiviewcontroller-example/) - Greetings, traveler! Today, I propose to discuss rarely used techniques, one of which is Method Swizzling. Method Swizzling allows you to replace your method directly in runtime while leaving the original implementation available. We will consider an option where we want to customize the navigation bar's appearance in the viewWillAppear method of the UIViewController. We - [Swift Dictionary default value](https://livsycode.com/swift/swift-dictionary-default-value/) - How to set and get values from a dictionary using a default value. - [The @autoclosure keyword](https://livsycode.com/swift/the-autoclosure-keyword/) - Greetings, traveler! We don't use the @autoclosure keyword very often. It turns a function argument into a closure. But how can we use it? Let's take a closer look at an example. Example Imagine we have a DataSource class that holds an array of data. For learning purposes, let's use an array of CustomStringConvertible. class - [How to create a weak protocol array](https://livsycode.com/swift/how-to-create-a-weak-protocol-array/) - Greetings, traveler! We often use weak object references, for example, when using the Delegate design pattern. Consider the following example: We have a Manager which has a delegate. The Manager has an update function. This function notifies the delegate to perform several actions defined in the delegate method. protocol ManagerDelegate: AnyObject { func manager(_ manager: - [FileManager directories: Documents vs Application Support vs tmp vs Caches](https://livsycode.com/best-practices/filemanager-directories-documents-vs-application-support-vs-tmp-vs-caches/) - Greetings, traveler! When saving data in the file system, we have various options. While the Documents directory has been a traditional choice, it's essential to be aware of other options, each with unique characteristics. Note By the way, Swift allows us to save data using not only the file system but also other tools. I - [Subscripts in Swift](https://livsycode.com/swift/subscripts-in-swift/) - Greetings, traveler! A subscripts provides us with a convenient tool to access collection, list, or sequence elements. For example, you have encountered them when using arrays and dictionaries. You can both retrieve an element and set or add a new value. Copyvar array = ["String"] let element = array[0] array[0] = "" var dict = - [Unowned vs weak. Are there any drastic benefits of using unowned references?](https://livsycode.com/best-practices/unowned-vs-weak-are-there-any-drastic-benefits-of-using-unowned-references/) - Greetings, traveler! Before ARC (Automatic Reference Counting) was introduced, developers had to manage memory and object references manually. ARC saved us a lot of headaches due to memory-related issues. However, we still need to manage references while working with reference types. When we don't use weak or unowned keywords, we signal to ARC that the - [Failable and throwing initializers](https://livsycode.com/best-practices/failable-and-throwing-initializers/) - Greetings, traveler! Sometimes, an object's initializer takes a particular type, but we must limit the possibility of passing some variants of values of this type to avoid initialization. Let's look at a practical example. We have a vehicle factory that can produce sedans and coupes. Note By the way, a factory can also be a - [Swift keypaths](https://livsycode.com/swift/swift-keypaths/) - Greetings, traveler! Swift keypaths have become a pretty popular feature since SwiftUI uses them a lot. So, let's talk about them a little. We have already discussed Swift keypaths in this article. Let's refresh our memory. Swift keypaths allow us to store a path to an object's property. Keypaths have cool features. Let's consider some of - [Dynamic Member Lookup in Swift](https://livsycode.com/swift/dynamicmemberlookup-in-swift/) - The Swift language has many convenient tools to make life easier and code more beautiful. Today, we will discuss one of them: the @dynamicMemberLookup attribute. - [Factory Method Design Pattern in Swift](https://livsycode.com/best-practices/factory-method-design-pattern-in-swift/) - We'll start our journey with creational patterns, and the first one we'll delve into is the Factory Method. - [UserDefaults vs FileManager vs Keychain vs Core Data vs SwiftData](https://livsycode.com/best-practices/userdefaults-vs-filemanager-vs-keychain-vs-core-data-vs-swiftdata/) - Greetings, traveler! Starting a new project where you will need to save data, you can face the choice of technology that will allow you to do this. In Swift, there are several options to choose from: UserDefaults FileManager Keychain Core Data SwiftData Let's determine what technology will be the most suitable for concrete cases. UserDefaults - [How to fix 'No exact matches in call to initializer' error in SwiftUI](https://livsycode.com/swift/how-to-fix-no-exact-matches-in-call-to-initializer-error-in-swiftui/) - Greetings, traveler! Many developers have encountered this compiler error in Xcode: No exact matches in call to initializer What exactly does that mean? Consider this example. Copyclass MyClass { let id: Int init(id: Int) { self.id = id } } let object = MyClass(id: "1") // ❌ The initializer of this class expects an Int - [callAsFunction vs @dynamicCallable](https://livsycode.com/swift/callasfunction-vs-dynamiccallable/) - Greetings, traveler! There are many hidden handy features in the Swift language. Today, we will talk about two of them: callAsFunction and @dynamicCallable. They offer pretty much the same functionality but have fundamental differences. Both of them allow us to mark a type as being directly callable. @dynamicCallable There are two types of languages: statically typed and - [Any vs AnyObject vs any in Swift](https://livsycode.com/swift/any-vs-anyobject-vs-any-in-swift/) - Greetings, traveler! Some tools in the Swift language have pretty similar names. I am talking about Any, AnyObject, and any. In this article, we will consider the differences between them. Any Any in Swift is a type that can represent any object, including instances of function types. Copylet array: [Any] = [ "Jack", 55, { - [The dump() function in Swift](https://livsycode.com/best-practices/the-dump-function-in-swift/) - Greetings, traveler! Developers have many tools for debugging, but we often use the print() function to output the value in the console. However, this is not too convenient in some cases. Consider this example. Copystruct Car { let maxSpeed = 300 let horsepower = 350 } let car = Car() print(car) Let's check the console. - [KVC](https://livsycode.com/swift/kvc/) - Greetings, traveler! KVC is a mechanism Cocoa provides that assists in accessing an object's properties using string identifiers. Example Consider this example. Let's create a class. Since KVC is connected with Objective-C, there are some limitations. Our class must inherit from the NSObject, and we need to mark its properties with the @objc dynamic attribute. - [KVO](https://livsycode.com/uikit/kvo/) - Greetings, traveler! Key-value observing (KVO) enables objects to be notified of changes to specific properties of another object. KVO is related to the KVC (Key-Value Coding). You can read more about it here. While KVO can be useful, some preparations are required to implement it in pure Swift code, as it relies on the Objective-C - [Swift Actors](https://livsycode.com/swift/swift-actors/) - Greetings, traveler! At the WWDC21 conference, Apple announced a new Actors feature that helps solve fundamental problems in asynchronous code. Here are these problems: Deadlocks arise when two or more processes are waiting for each other to complete, preventing neither process from progressing. Starvation is when a process cannot access necessary resources, and the program - [Task.detached in Swift](https://livsycode.com/swift/task-detached-in-swift/) - Greetings, traveler! We continue to study our course on Swift Concurrency. This article will examine the difference between a task and a detached task. The answer to this question is straightforward. Detached tasks don't inherit anything from the caller. But what can a task inherit from a caller? Let's take a closer look. Tasks can inherit - [AsyncStream in Swift](https://livsycode.com/swift/asyncstream/) - Greetings, traveler! To learn more about AsyncStream in the Swift programming language, we can look at the protocol it conforms to, known as AsyncSequence. As described in Apple's documentation: A type that provides asynchronous, sequential, iterated access to its elements. An AsyncSequence resembles the Sequence type — offering a list of values you can step through one at a - [Actor reentrancy](https://livsycode.com/swift/actor-reentrancy/) - Greetings, traveler! We continue the cycle of our conversations about Swift Concurrency. In the previous article, we discussed the actors. In this article, we will continue to discuss them and consider one of the problems that may arise when using them. That's where we last left off: The actor's methods are placed in a queue - [Sendable and @Sendable closures in Swift](https://livsycode.com/swift/sendable-and-sendable-closures-in-swift/) - Greetings, traveler! Swift has data types that can be safely transferred from one thread to another. SE-0302 introduces a straightforward way to separate the wheat from the chaff — the sendable data types marked with the Sendable protocol. Sendable Basic types Many data types from the standard library are Sendable by default. "Basic" data types - [@AppStorage SwiftUI property wrapper](https://livsycode.com/swiftui/appstorage-swiftui-property-wrapper/) - Greetings, traveler! SwiftUI has a fancy property wrapper for reading values from UserDefaults. It's pretty convenient because it automatically updates your view's body property whenever the value in UserDefaults changes. Basically, it keeps an eye on a specific key in UserDefaults and refreshes your UI if that key changes. By default, @AppStorage monitors UserDefaults.standard, but if you wish, you can instruct it - [The nonisolated and the isolated keywords in Swift](https://livsycode.com/swift/the-nonisolated-and-the-isolated-keywords-in-swift/) - Greetings, traveler! Swift actor isolation is a Swift Concurrency feature that allows actors to restrict concurrent access to their state. SE-313 introduced two keywords to handle actor isolation: isolated and nonisolated. By the way, you can read more about actors and Swift Concurrency to delve deeper into this topic. isolated By default, all methods and properties - [SwiftUI Coordinator. Part 1: TabView and NavigationStack](https://livsycode.com/swiftui/swiftui-coordinator-part-1-tabview/) - SwiftUI Coordinator. In this tutorial, we will learn the basics of this approach and will create a TabView (or a TabBar). This is the first part of this series. - [SwiftUI Coordinator. Part 3: Router](https://livsycode.com/swiftui/swiftui-coordinator-part-3-router/) - Today, we will discuss one of the essential participants in this story — the Router. This is the third part of our SwiftUI Coordinator tutorial/ - [SwiftUI TextEditor with placeholder](https://livsycode.com/swiftui/swiftui-texteditor-with-placeholder/) - Apple has yet to provide a built-in solution for creating a placeholder in TextEditor. However, creating a custom view for this purpose is not difficult. - [Observer Design Pattern in Swift](https://livsycode.com/best-practices/observer-design-pattern-in-swift/) - Greetings, traveler! We continue to discuss Design Patterns. In this article, we will analyze the Observer Pattern. You have likely encountered this pattern multiple times in your work. Many tools based on this pattern, such as Notification Center and KVO, as well as well-known reactive frameworks like RxSwift, are built on its foundation. The Observer is a design pattern that enables you to define a mechanism for notifying multiple objects when - [State Design Pattern in Swift](https://livsycode.com/best-practices/state-design-pattern-in-swift/) - Greetings, traveler! It is the turn of a new Behavioral Design Pattern — the State. The State is a pattern that allows you to dynamically change the behavior of an object when its state changes. This pattern is handy when an object needs to change its behavior because of state changes while keeping the logic - [Strategy Design Pattern in Swift](https://livsycode.com/best-practices/strategy-design-pattern-in-swift/) - Greetings, traveler! We continue to talk about Design Patterns. Next up is a behavioral design pattern, which is the Strategy. Strategy is a design pattern that defines a set of related algorithms and encapsulates them into their own objects. This allows the algorithms to be easily swapped out, making it easier to customize the app's - [Visitor Design Pattern in Swift](https://livsycode.com/best-practices/visitor-design-pattern-in-swift/) - Greetings, traveler! Welcome to the next part of our Design Pattern series. Today, we delve into the Visitor pattern. This behavioral design pattern allows you to enhance the functionality of an object hierarchy without altering the existing code, a feature that can be particularly beneficial in specific scenarios. Imagine you're working on a project with several - [The some and the any keywords in Swift](https://livsycode.com/best-practices/the-some-and-the-any-keywords-in-swift/) - What is the difference between "some" and "any" keywords, and when should they be used? - [The defer keyword in Swift](https://livsycode.com/best-practices/the-defer-keyword-in-swift/) - How can you use the defer keyword to make your code safer? Here, you can find a practical example with closures and an analysis of this keyword's applicability. - [Async/await in Swift](https://livsycode.com/swift/async-await-in-swift/) - Greetings, traveler! Async/await is a new approach to multithreading in Swift. It simplifies writing complex call chains and makes the code readable. Async/await is part of Swift Concurrency, allowing multiple code pieces to run simultaneously. To begin with, let's examine an example of code that we can modify using Swift Concurrency. We will create a - [Tasks in Swift](https://livsycode.com/swift/tasks-in-swift/) - Greetings, traveler! In the last article, we discussed the basics of async/await and settled on Tasks. Tasks allow you to perform various operations in an asynchronous context simultaneously. You can place calls to asynchronous methods inside a single task or split them into several. In that article, we considered this use case. Copyfunc loadImage(url: URL) - [Async let in Swift](https://livsycode.com/swift/async-let-in-swift/) - I would like to take a closer look at the possibilities of asynchronously executing operations within a single Task using async let. - [How to cancel a Task in Swift](https://livsycode.com/swift/how-to-cancel-a-task-in-swift/) - Greetings, traveler! When working with Concurrency in Swift, we can cancel a task by calling its cancel() method. However, it is important to note that this cancellation is cooperative, which implies that the task must periodically check if it has been canceled via Task.isCancelled and take appropriate actions. Moreover, you can call the Task.checkCancellation() method ## Pages - [Podcasts](https://livsycode.com/podcasts/) - Designing a Dynamic Retail Home Page on iOS Modern iOS Performance Myths: Episode 1 - [Agent Skills](https://livsycode.com/agent-skills/) - iOS Performance Agent Skills A collection of AI-agent skills for reviewing, diagnosing, and improving performance in iOS applications. iOS Clean Architecture Agent Skills An Agent Skill for designing, reviewing, and simplifying Clean Architecture composition in Swift and iOS applications. iOS Testing Strategy Agent Skill A reusable AI-agent skill for designing, reviewing, and improving testing strategies - [Series](https://livsycode.com/series/) - System Design Practical insights into designing scalable, maintainable software systems — for real-world applications and technical interviews. Writing code without bugs or unnecessary headaches. Explore Interview Preparation Technical deep dives into concepts commonly explored during iOS engineering interviews, including language internals, architecture, and performance topics. Explore Foundation Models Notes, tips, and examples on working with - [About](https://livsycode.com/about/) - I am an iOS Mentor. Currently, I hold the position of a Staff Software Engineer and Development Team Leader at a fintech company. I am glad to see you here. ## Categories - [Blog](https://livsycode.com/category/blog/) - Your blog category - [SwiftUI](https://livsycode.com/category/swiftui/) - [UIKit](https://livsycode.com/category/uikit/) - [Best Practices](https://livsycode.com/category/best-practices/) - [Swift](https://livsycode.com/category/swift/) - [DSA](https://livsycode.com/category/dsa/) ## Tags - [SwiftUI Custom TextField](https://livsycode.com/tag/swiftui-custom-textfield/) - A Custom SwiftUI text field with flexible customization, input mask, and validation. Made with UITextField and UIViewRepresentable. - [SwiftUI Coordinator](https://livsycode.com/tag/swiftui-coordinator/) - A fully developed iOS application based on the SwiftUI framework and MVVM+Coordinator architecture. - [Code](https://livsycode.com/tag/code/) - Tips and code examples. - [Design Patterns](https://livsycode.com/tag/design-patterns/) - Design patterns are practical solutions to common software architecture problems in your software development arsenal. In this series of articles, we will briefly analyze the main ones with examples. - [Concurrency](https://livsycode.com/tag/concurrency/) - The native concurrency system in Swift enables developers to create parallel and asynchronous operations with minimal overhead and high efficiency, making it a suitable choice for concurrent programming. - [SwiftData](https://livsycode.com/tag/swiftdata/) - Tips and code examples. - [SwiftUI Week Calendar View](https://livsycode.com/tag/swiftui-week-calendar-view/) - Infinite SwiftUI Week Calendar View with flexible customization tutorial. Source code provided. - [Underscore attributes](https://livsycode.com/tag/underscore-attributes/) - While these attributes can seem like a convenient tool, we should remember that they can be unstable. The semantics of these attributes are subject to change and most likely need to go through the Swift evolution process before being stabilized. - [LeetCode Blind 75](https://livsycode.com/tag/leetcode-blind-75/) - The Blind 75 is one of the most recognized problem sets for coding interview preparation. It was curated to cover the essential data structures, algorithms, and problem-solving patterns that appear frequently in technical interviews. - [Notes](https://livsycode.com/tag/notes/) - Less about syntax, more about meaning. - [System Design](https://livsycode.com/tag/system-design/) - Practical insights into designing scalable, maintainable software systems — for real-world applications and technical interviews. Writing code without bugs or unnecessary headaches. - [AI](https://livsycode.com/tag/ai/) - Thoughts on how AI is reshaping software development, skills, and engineering practice. - [Foundation Models](https://livsycode.com/tag/foundation-models/) - Notes, tips, and examples on working with Apple Foundation Models in Apple platforms. - [Interview Preparation](https://livsycode.com/tag/interview-preparation/) - Technical deep dives into concepts commonly explored during iOS engineering interviews, including language internals, architecture, and performance topics. - [Agent Skills](https://livsycode.com/tag/agent-skills/) - [Performance](https://livsycode.com/tag/performance/)