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

前端 未结 7 1810
感情败类
感情败类 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条回答
  •  猫巷女王i
    2020-12-08 07:29

    Generally, you would make use of structures over classes when the data you are defining is relatively simple, you don’t need to worry about referencing, or you don’t need to inherit another data structure’s properties and methods.

    If you have data that should not be changed after initialization we can ensure that at compile time when using structs.

    Use classes for situations where you know that the identity of the object is going to be important. In other words, use classes where you want multiple regions of code to be pointing at the very same instance of the the object.

    Use structs for situations where you know that the value of the object matters. In other words, structs are great for situations where it doesn’t matter if two different regions of code are referring to the very same instance of to copy of the instance

    If you need to share mutable state between parts of you program you should use a class.

    If you need inheritance or you know you want to pass references to an object around, use a class.

提交回复
热议问题