UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Question: Struct or Class for user accounts?

Forums > 100 Days of SwiftUI

@boat  

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

2      

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.

2      

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.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.