Classes and Structures have a great deal 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
For information on these features, please search the specific section.
Classes however, have functionality that Structures do not, namely:
- 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.
These are all advanced features. Please see the relevant sections for them.
Classes and Structures are defined in an analogous way to C-based languages, using the struct
and class
keywords:
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
Classes and Structures are instantiated in the same way:
let someResolution = Resolution()
let someVideoMode = VideoMode()
Both classes and structures use a simple dot-based (class.property
) based syntax to access properties and subproperties:
print("The width of someResolution is \(someResolution.width)")
// Prints "The width of someResolution is 0"
print("The width of someVideoMode is \(someVideoMode.resolution.width)")
// Prints "The width of someVideoMode is 0"
Structures, and only structures, receive an automatically-generated memberwise initializer which you can use to initialise properties.
let vga = Resolution(width: 640, height: 480)