NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

Question: Struct or Class for user accounts?

Forums > 100 Days of SwiftUI

Hi I'm thinking of the infrasturcture of my app.

For users, are Struct or Class used as common practice ?

Paul said: In Swift, Struct is more for UI, and Class is more for Data.

I firstly thought that Struct is better as every instance is unique, just like each user account which should be unique.

Then it occurs to me that "Shouldn't user acccount be kinda of data, and need to updated across the platform when one change made (Paul said that if user wanted to change his username, it needed to be updated at multiple places across the platform, hence the Class's data-reference feature should kick in)

Should I keep reading as there might be something more useful coming along , rather than Struct or Classes ?

Thanks

Boat

1      

Structs are value types and Classes are reference types. F.e. when you don't do any work on your instance and you don't pass it in different functions or to other objects, than you can use a struct. But when you make changes to your instance and want to pass it to other functions and/or objects than use a class. When you pass a struct it passes a copy of the instance and not a instance itself. If you make changes to the copy the original is untouched. If you pass a class a reference to the object is passed and all changes you make is passed to the original instance. That's the difference.

https://developer.apple.com/swift/blog/?id=10

Look at your use case and decide which fits better to your needs.

1      

I think this:

Paul said: In Swift, Struct is more for UI, and Class is more for Data.

refers to how SwifUI uses structs for its views like this:

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
    }
}

and classes are used to share data across different views, like in the iExpense project7, days 36-38.

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.