Structs and Classes
Similarities
-
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
-
Whenever you define a new structure or class, you define a new Swift type.
-
Give types
UpperCamelCasenames (such asSomeStructureandSomeClasshere) to match the capitalization of standard Swift types (such asString,Int, andBool). -
Give properties and methods
lowerCamelCasenames (such asframeRateandincrementCount) to differentiate them from type names.
-
Creation
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
Instantiation
let someResolution = Resolution()
let someVideoMode = VideoMode()
Property Access
print("The width of someResolution is \(someResolution.width)")
// Prints "The width of someResolution is 0"
someVideoMode.resolution.width = 1280
print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
// Prints "The width of someVideoMode is now 1280"
Struct-Exclusive
-
Are Value Types .
"Advantages" of Structs
-
Value Type vs Reference Type :
-
Reference types can be harder to reason about (such as Classes).
-
If instances of the same Class were far apart in your programβs code, it could be difficult to find all the ways that the video mode is changed. Wherever you use one, you also have to think about the code that uses the other, and vice versa.
-
-
In contrast, value types (such as Structs) are easier to reason about because all of the code that interacts with the same value is close together in your source files.
-
Initialization
let vga = Resolution(width: 640, height: 480)
Class-Exclusive
-
Are Reference Types .
What a Class Has Extra
-
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.