-1

Here's my scenario:

I have a list of user present in a TableView, in each row I show some user's information like address, phone number.

I can tap on a user, I pass the user to another screen like Detail View Controller, in here I can change the user's information. Then I can tap back and those change affect to TableView.

In the scenario above, what class or struct should I use. I've tried both, class might be easier when I only need to modify user's info in the Detail View Controller but can it lead any side effect ?

I've read some article and they says that always choose struct by default but it make me confused Some one can give me some advice when to use one instead of another and explain why. Thanks a lot.

Tung Vu Duc
  • 1,552
  • 1
  • 13
  • 22

2 Answers2

0

If you choose class then you don't need to do anything just pass the same object which exists in the user's array.

If you choose struct it will call by value and will not change anything in another instance, so you will need to inform your ViewController regarding the changes (May be in back button click) via delegate or notification. You can pass your user model in the delegate call back or notification object and replace it in your user's array by comparing its id.

TheTiger
  • 13,264
  • 3
  • 57
  • 82
  • Yes. It is. The question I ask is which is better for this case, and for another case. When to use class and when to struct – Tung Vu Duc Aug 26 '19 at 06:25
  • 1
    There is nothing bad and better. You can use any one. But remember `structs` executes faster than `classes` but in normal apps this can be ignored. `structs` are also easily encodable and decodable with json but this is different thing and depends on your app requirement. Just the case you mentioned in the question you should not have any issue with both of them. – TheTiger Aug 26 '19 at 06:30
0

Its better to use structs because they are value types and have a unique memory address(creates a copy). In your case its better because you have multiple users and each user will be unique. Instead if you use classes for user and if there are multiple instances of the same user then changing the properties of one user will change another because classes are reference types and points to the same memory address.

Atmaram
  • 494
  • 4
  • 14