How should I reason when I have to choose between a class, struct and enum in Swift?

前端 未结 7 1796
感情败类
感情败类 2020-12-08 07:16

Since classes, structs and enums all has constructors, properties and computed properties, how should I reason when choosing between them?

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 07:27

    I think it's quite a refined discussion! I like the thoughts expressed here: http://www.swift-studies.com/blog/2014/7/1/struct-enum-or-class

    There's quite a lot of details, and their recommendations. I've copied their summary here, but it's a whole article

    • enums are initialised by one of a finite number of cases, are completely defined by their case, and should always be valid instances of that case when instantiated
    • structs should be used when there is not a finite number of valid instances (e.g. enum cases) and the struct also does not form a complete definition of an object, but rather an attribute of an object
    • A class completely defines a primary actor in your object model, both its attributes and its interactions.

提交回复
热议问题