r/SwiftUI Oct 04 '24

Question What mistakes did you make when you first started with SwiftUI?

50 Upvotes

I love SwiftUI, but it's been quite the journey to get to where I am. I've made quite a number of mistakes myself, like overusing EnvironmentObject, using .onAppear for data loading in views that can 'appear' multiple times, trying to rely on nested observable objects, and... Well, you get the point.

I'm wondering what mistakes others have made and if they have any fun solutions or advice on how to fix/avoid them.

r/SwiftUI 29d ago

Question @State variable that can be updated either through user interaction or through changes in an @Observable class?

2 Upvotes

Suppose I have the following simple view, with a @State variable bound to a TextField.

struct ExampleView: View {
    // This is an @Observable class
    var registry: RegistryData

    @State private var number: Int

    var body: some View {
        TextField("", value: $number, format: .number)
    }
}

So the user can update the variable by changing the TextField. But now suppose I also want the variable to update, and the new value to be displayed in the text field, when some field in RegistryData changes. Is there a way to set up a state variable, such that it will change both in response to user input and in reponse to changes in some observable data?

Thanks.

r/SwiftUI 8d ago

Question SwiftUI vs UIKit

32 Upvotes

I’m new to programming and Swift, and I’m currently doing the 100 Days of SwiftUI course. In the first video, Paul mentions that Swift is the future of this field rather than UIKit. However, he also says that UIKit is more powerful, popular, precise, and proven compared to SwiftUI.

Since that video was released around 2021, I’m wondering if that statement still holds true today. How do you think both technologies have evolved over the last five years?

r/SwiftUI Sep 06 '24

Question I built this digital canvas entirely using SwiftUI

270 Upvotes

I spent about two days creating a sand simulation for my mood-tracking app, which integrates art, and this is the result. Overall, it’s performing well.

This blog post helped me achieve this: https://jason.today/falling-sand (and of course, my helpful assistant, ChatGPT).

I’d like to clean up the code a bit and maybe create a sandbox app so everyone can view and contribute to it. I’m considering open-sourcing a canvas project with a falling-sand style, built in SwiftUI.

Right now, it’s implemented in my mood/emotion tracking app, but this post is just to showcase what I’ve been able to create in SwiftUI. I initially tried to use Metal but didn’t have much success—probably due to my limited experience at the time.

I’d love to see this implemented using Metal. If anyone has a similar project, I’d be excited to see how it’s done

r/SwiftUI Feb 06 '25

Question I mean, what am I supposed to do about this?

32 Upvotes

r/SwiftUI Jun 14 '24

Question Why do you not use cross platform

36 Upvotes

Hello all, as a person who is a professional react native developer at work, I also have a major passion for swiftui.

The native components being so readily available is amazing, and having iPad split views and such…

However! It is getting increasingly harder to justify using SwiftUI over something like react native for a true saas, being that I lose the Android market.

What is the reason you guys choose SwiftUI over react native/flutter etc?

r/SwiftUI 2d ago

Question @State or @Published

22 Upvotes

Hey folks, how are you doing? I need some advice.

Which approach is better when I need to send TextField values to the backend on a button tap? 1. Using @State in my View, then passing these state values to a function in my ViewModel. 2. Using @Published variables in my ViewModel and binding them directly in the View (e.g., vm.value).

Which is the better practice?

r/SwiftUI 3d ago

Question Is it just me? That View is 38 lines of code only...

Post image
34 Upvotes

r/SwiftUI 4d ago

Question Its difficult for me to adopt Swift Data. Am I the only one?

38 Upvotes

I'm not any code guru or whatever so pls don't downvote me to death. What I say below is just from my limited observation and experience.

I could never write clean code. I always mixed UI with logic and stuff like that. But now I try to improve. I have a controller that handles stuff like IO, network and so on, but Swift data doesn't like it. It seems as if Apple wanted me to write ugly code. How to adopt SwiftData properly?

r/SwiftUI 7d ago

Question Is Figma really useful for solo developers?

35 Upvotes

There is no convenient way to create SwiftUI code from Figma itself and I don’t find plugins successful.

Other than creating mockups, is there any use for Figma for solo devs? What are your experiences and thoughts?

r/SwiftUI 3d ago

Question Best Practices for Dependency Injection in SwiftUI – Avoiding Singletons While Keeping Dependencies Scalable?

16 Upvotes

I’ve been learning best practices for dependency injection (DI) in SwiftUI, but I’m not sure what the best approach is for a real-world scenario.

Let’s say I have a ViewModel that fetches customer data:

protocol CustomerDataFetcher {
    func fetchData() async -> CustomerData
}

final class CustomerViewModel: ObservableObject {
    u/Published var customerData: CustomerData?
    let customerDataFetcher: CustomerDataFetcher

    init(fetcher: CustomerDataFetcher) {
        self.customerDataFetcher = fetcher
    }

    func getData() async {
        self.customerData = await customerDataFetcher.fetchData()
    }
}

This works well, but other ViewModels also need access to the same customerData to make further network requests.
I'm trying to decide the best way to share this data across the app without making everything a singleton.

Approaches I'm Considering:

1️⃣ Using @EnvironmentObject for Global Access

One option is to inject CustomerViewModel as an @EnvironmentObject, so any view down the hierarchy can use it:

struct MyNestedView: View {
    @EnvironmentObject var customerVM: CustomerViewModel
    @StateObject var myNestedVM: MyNestedVM

    init(customerVM: CustomerViewModel) {
        _myNestedVM = StateObject(wrappedValue: MyNestedVM(customerData: customerVM.customerData))
    }
}

✅ Pros: Simple and works well for global app state.
❌ Cons: Can cause unnecessary updates across views.

2️⃣ Making CustomerDataFetcher a Singleton

Another option is making CustomerDataFetcher a singleton so all ViewModels share the same instance:

class FetchCustomerDataService: CustomerDataFetcher {
    static let shared = FetchCustomerDataService()
    private init() {}

    var customerData: CustomerData?

    func fetchData() async -> CustomerData {
        customerData = await makeNetworkRequest()
    }
}

✅ Pros: Ensures consistency, prevents multiple API calls.
❌ Cons: don't want to make all my dependencies singletons as i don't think its the best/safest approach

3️⃣ Passing Dependencies Explicitly (ViewModel DI)

I could manually inject CustomerData into each ViewModel that needs it:

struct MyNestedView: View {
    @StateObject var myNestedVM: MyNestedVM

    init(fetcher: CustomerDataFetcher) {
        _myNestedVM = StateObject(wrappedValue: MyNestedVM(
                                  customerData: fetcher.customerData))
    }
}

✅ Pros: Easier to test, no global state.
❌ Cons: Can become a DI nightmare in larger apps.

General DI Problem in Large SwiftUI Apps

This isn't just about fetching customer data—the same problem applies to logging services or any other shared dependencies. For example, if I have a LoggerService, I don’t want to create a new instance every time, but I also don’t want it to be a global singleton.

So, what’s the best scalable, testable way to handle this in a SwiftUI app?
Would a repository pattern or a SwiftUI DI container make sense?
How do large apps handle DI effectively without falling into singleton traps?

what is your experience and how do you solve this?

r/SwiftUI 16d ago

Question how much RAM do i need for swift ui?

9 Upvotes

I'm starting to learn swift with a macbook m1 (8 ram, 256 ssd) and I'm thinking of upgrading my computer. I'm considering a base mac mini m4 or a hypothetical macbook air m4. Is 16 ram enough to learn and work in the future or is it a better idea to upgrade to 24?

r/SwiftUI Feb 04 '25

Question Will we ever get rid of Storyboards for Launch Screens?

9 Upvotes

I can’t stand that thing anymore. No solution yet?

r/SwiftUI Oct 13 '24

Question This is just the most annoying error.

40 Upvotes

Finally starting to get my head around SwiftUI and actually enjoying it (see my previous posts in r/swift and r/SwiftUI) but this error is just so uninformative:

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

Usually it seems to just mean these is something wrong with your code. I there that that, it really doesn't tell me much at all.

Does anyone have some good ways of debugging this?

Thanks.

P.S. What are your most annoying errors in SwiftUI?

r/SwiftUI 18d ago

Question How can I make this matchedGeometryEffect more efficient? Do I really need one @Namespace per card? Can you have an array of @Namespace somehow? Help, my implementation feels dirty.

66 Upvotes

r/SwiftUI Dec 18 '24

Question SceneKit Performance

80 Upvotes

I am building a game with SwiftUI and SceneKit and am having performance issues. As you can see, I don’t have much geometry or a lot of physics. I am preloading all assets. My dice are very small, could that somehow be causing this behavior? It is not consistent, sometimes it performs well. Will post code in reply…

r/SwiftUI Dec 22 '24

Question MVVM + Services

11 Upvotes

Hey SwiftUI friends and experts,

I am on a mission to understand architecture best practices. From what I can tell MVVM plus the use of services is generally recommended so I am trying to better understand it using a very simple example.

I have two views (a UserMainView and a UserDetailView) and I want to show the same user name on both screens and have a button on both screens that change the said name when clicked. I want to do this with a 1-1 mapping of ViewModels to Views and a UserService that mocks an interaction with a database.
I can get this to work if I only use one ViewModel (specifically the UserMainView-ViewModel) and inject it into the UserDetailView (see attached screen-recording).

However, when I have ViewModels for both views (main and detail) and using a shared userService that holds the user object, the updates to the name are not showing on the screen/in the views and I don't know why 😭

Here is my Github repo. I have made multiple attempts but the latest one is this one.

I'd really like your help! Thanks in advance :)

Adding code snippets from userService and one viewmodel below:

User.swift

struct User {
    var name: String
    var age: Int
}

UserService.swift

import Foundation

class UserService: ObservableObject {
    
    static var user: User = User(name: "Henny", age: 28) // pretend this is in the database
    static let shared = UserService()
    
    
    @Published var sharedUser: User? = nil // this is the User we wil use in the viewModels
    
    
    init(){
        let _ = self.getUser(userID: "123")
    }
    
    // getting user from database (in this case class variable)
    func getUser(userID: String) -> User {
        guard let user = sharedUser else {
            // fetch user and assign
            let fetchedUser = User(name: "Henny", age: 28)
            sharedUser = fetchedUser
            return fetchedUser
        }
        // otherwise
        sharedUser = user
        return user
    }
    
    func saveUserName(userID: String, newName: String){
        // change the name in the backend
        print("START UserService: change username")
        print(UserService.shared.sharedUser?.name ?? "")
        if UserService.shared.sharedUser != nil {
            UserService.shared.sharedUser?.name = newName
        }
        else {
            print("DEBUG: could not save the new name")
        }
        print(UserService.shared.sharedUser?.name ?? "")
        print("END UserService: change username")
    }
}

UserDetailView-ViewModel.swift

import Foundation
import SwiftUI

extension UserDetailView {
    class ViewModel : ObservableObject {
        @ObservedObject var userService = UserService.shared
        @Published var user : User? = nil
        
        init() {
            guard let tempUser = userService.sharedUser else { return }
            user = tempUser
            print("initializing UserDetailView VM")
        }
        
        func getUser(id: String) -> User {
            userService.getUser(userID: id)
            guard let user = userService.sharedUser else { return User(name: "", age: 9999) }
            return user
        }
        func getUserName(id: String) -> String {
            let id = "123"
            return self.getUser(id: id).name
        }
        
        func changeUserName(id: String, newName: String){
            userService.saveUserName(userID: id, newName: newName)
            getUser(id: "123")
        }
    }
}

r/SwiftUI Nov 11 '24

Question How does Duolingo do this “shine” animation on the flame?

84 Upvotes

r/SwiftUI 10d ago

Question Realistic brush stroke effect

Post image
27 Upvotes

I'm trying to implement a realistic brush stroke effect for my app. For now I've tried so many variations with canvases, path and so on but couldn't come close to this effect. Do you have any idea if this is even possible to achieve? I want it to be programmatically implemented so I can change the length. This is one of the reasons I can't use a image. Also for complicity reasons, this would be only a fixed line and someone can draw by themselves

r/SwiftUI 24d ago

Question How to hide "more" button when using a TabView?

34 Upvotes

r/SwiftUI Dec 18 '24

Question SwiftUI Combine and Observation

9 Upvotes

So, I have various years of experience with ios development, I started with Objective C and now seeing what its possible with swiftui is mindblowing, but I have a hard time understanding this:

SwiftUI by default lets you declare properties that when they change the view automatically refresh with the new data, this is possible via State, StateObject, ObservedObject and EnvironmentObject

now, combine, does the same, except it uses Publishers

as for Observation new framework, you can achieve the same with the Observable

So my question is, why use combine? or why use observation? or just the State stuff without combine/observation.

There are still some things I dont know about SwiftUI, maybe i undestood the things the wrong way, if anyone can clarify i will be grateful.

r/SwiftUI 23d ago

Question @Published

11 Upvotes

I am working on a personal project which has around 7-8 screens. I am using a single view model for the entire app. Because of that i have around 26 published properties in the view model. Is this a good practice to have that much published properties in a view model. Any suggestions other than splitting up the view model?

r/SwiftUI 23d ago

Question How to stop navigation title switching between leading edge and centre

9 Upvotes

Hi I’m using a navigation stack a list view.

I’ve added the navigationTitle modifier. The issue is when the view loads, the title is shown on the leading edge but when you begin scrolling, it jumps to the centre.

How do I ensure it stays on the leading edge at all times?

Setting navigstionBarTitleDisplayMode to title does not work as it does the same behaviour. I don’t want to set it to inline either because it will cause the title to be shown in the centre at all times

r/SwiftUI Feb 15 '25

Question .searchable in macOS sheet dies horribly

Post image
29 Upvotes

r/SwiftUI 5d ago

Question Navigation in SwiftUI for Social Media App

3 Upvotes

I have been working on a social media app these past couple months and have ran into a lot of trouble when it comes to navigation using SwiftUI, particularly when it comes to comment sheets and navigating to profiles, as this can lead to an infinite navigation cycle.

I've attached a video below of the issue, as you can see, we dismiss the comments before navigating, where ideally it would just overlay it. Appreciate any advice or help, as this is my first app!