Why Choose Struct Over Class?

前端 未结 16 2366

Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offeri

16条回答
  •  清歌不尽
    2020-11-22 06:21

    Some advantages:

    • automatically threadsafe due to not being shareable
    • uses less memory due to no isa and refcount (and in fact is stack allocated generally)
    • methods are always statically dispatched, so can be inlined (though @final can do this for classes)
    • easier to reason about (no need to "defensively copy" as is typical with NSArray, NSString, etc...) for the same reason as thread safety

提交回复
热议问题