Comparing Structures and Classes
Structures and classes in Swift have many things in common. Both can:
- Define properties to store values
- Define methods to provide functionality
- Define subscripts to provide access to their values using subscript syntax
- Define initializers to set up their initial state
- Be extended to expand their functionality beyond a default implementation
- Conform to protocols to provide standard functionality of a certain kind
Classes have additional capabilities that structures don’t have:
- Inheritance enables one class to inherit the characteristics of another.
- Type casting enables you to check and interpret the type of a class instance at runtime.
- Deinitializers enable an instance of a class to free up any resources it has assigned.
- Reference counting allows more than one reference to a class instance.
The Resolution
structure definition and the VideoMode
class definition only describe what a Resolution
or VideoMode
will look like. They themselves don’t describe a specific resolution or video mode. To do that, you need to create an instance of the structure or class.
The syntax for creating instances is very similar for both structures and classes:
let someResolution = Resolution()let someVideoMode = VideoMode()
Structures and classes both use initializer syntax for new instances. The simplest form of initializer syntax uses the type name of the class or structure followed by empty parentheses, such as Resolution()
or VideoMode()
. This creates a new instance of the class or structure, with any properties initialized to their default values. Class and structure initialization is described in more detail in Initialization.
You can access the properties of an instance using dot syntax. In dot syntax, you write the property name immediately after the instance name, separated by a period (.
), without any spaces:
print("The width of someResolution is \(someResolution.width)")// Prints "The width of someResolution is 0"
In this example, someResolution.width
refers to the width
property of someResolution
, and returns its default initial value of 0
.
You can drill down into subproperties, such as the width
property in the resolution
property of a VideoMode
:
print("The width of someVideoMode is \(someVideoMode.resolution.width)")// Prints "The width of someVideoMode is 0"
You can also use dot syntax to assign a new value to a variable property:
someVideoMode.resolution.width = 1280print("The width of someVideoMode is now \(someVideoMode.resolution.width)")// Prints "The width of someVideoMode is now 1280"