When to use a value type?

It is often said that you should always start with a struct and change to a different type when needed. This is great advice for a lot of cases because structs are often fine for most cases. However, structs aren't the only value type, and it's always good to not default to using certain things blindly. If you need an object that represents a finite set of possible states or results, such as a network-connection state, a traffic-light state, or a limited set of valid configuration options for your app, you will likely need an enum. Regardless of the value semantics that make value types great, an enum is a great way to avoid typos and represent a state. It's often pretty clear when you should use an enum due to its nature.

Structs are used for objects that do not have an identity. In other words, it makes sense to pass copies of it around. A good example of this is when you create a struct that can communicate with the network or a database. This struct would have no identity because it's mostly a collection of properties and methods that aren't associated with a single version of the struct.

A good example of a struct is the CGPoint struct that you read about at the beginning of this structure. A CGPoint represents a location in a two-dimensional grid. It has no identity, and passing copies of it around makes sense. It only contains two properties, so it doesn't require any inheritance. These features make it a great candidate to be implemented as a value type.

If you follow the advice of always starting with a struct, try to figure out reasons for your new object to not be a struct. If you find a good reason to not use a struct, then make it a class. Often you won't be able to find a good reason to use a class instead of a struct. If this is the case, make your new object a struct; you can always switch to using a class later. It's usually harder to switch from a class to a struct due to the stricter rules regarding mutability and the lack of subclassing for structs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset