Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between struct and typealias in swift?

I want to have an array with one string and one integer in it. What's the difference between:

struct People { var name: String!; var age: Int! };
var data = Array<People>();
data.append (People(name: "John Doe", age: 31));

with:

typealias People = (name: String!, age: Int!);
var data = Array<People>();
data.append ((name: "John Doe", age: 31));

in terms of everything other than that. I mean, is there any difference in accessing the data, memory management, pointer-issue things, or something else I should be wary of when switching from struct to typealias? I usually use struct, but then I just found that I have typealias as alternative. I just want to make sure which one is better for my daily use. Note: I notice that struct is much like class in terms of you can add methods in there. But for things like that, I usually straight up using class.

like image 850
Chen Li Yong Avatar asked Feb 06 '23 20:02

Chen Li Yong


1 Answers

You are comparing a struct with the typealias of a tuple.

A struct is much more powerful than a tuple, here's some advantages only a struct offers

  1. a struct can conform to a protocol, a tuple can't
  2. a struct can have methods, a tuple can't
  3. a struct can have computed properties, a tuple can't
  4. a struct can have initializers, a tuple can't

Considerations

I suggest you to use a struct for your model. It's a better fit for a model value.

Someday you'll need to add a computed property (like birthYear) to your type and you don't want to be constrained by the limitations of simple tuple.

like image 164
Luca Angeletti Avatar answered Feb 08 '23 14:02

Luca Angeletti