classes
The struct keyword defines structure.
The class keyword defines class.
Both structures and classes 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
Additionally for classes
- classes can participate in inheritance
- you can check and interpret the type of a class instance at runtime
- you can define deinitializer to free up any resources it has assigned
- Automatic Reference Counting (ARC) automatically frees up the memory used by class instances when those instances are no longer needed
The . operator is used to access to the members from outside of class.
struct Resolution {
var width = 0
var height = 0
fun area() -> Int {
return width*height
}
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
fun myFunc(){/* ... */}
}
let someResolution = Resolution()
let someVideoMode = VideoMode()
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"
Classes are copied by reference, structures are copied by value.
class A {
var str = "A"
}
var a = A()
var aCopy = a
aCopy.str = "b"
print(a.str) // print b
struct B {
var str = "B"
}
var b = B()
var bCopy = b
bCopy.str = "c"
print(b.str) // print B
print(bCopy.str) // print c