- 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.
Structures are always copied when they are passed around in your code, and do not use reference counting.
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var framerate = 0.0
var name: String?
}
var hd = Resolution(width:30,height:100)
var tmpHd = hd
tmpHd.width = 120
//sturct and enumeration are value types
print("sturct \(hd.width) != \(tmpHd.width). copied")
var c = VideoMode()
c.resolution.width = 200
c.resolution.height = 300
var tmpC = c
tmpC.resolution.width = 120
/*
class is reference type
identical operator : === , !==
*/
print("class \(c.resolution.width) == \(tmpC.resolution.width). reference")
if c === tmpC {
print ("class identical operator. equal")
}
// else if c !== tmpC
As a general guideline, consider creating a structure when one or more of these conditions apply:
- The structure’s primary purpose is to encapsulate a few relatively simple data values.
- It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
- Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
- The structure does not need to inherit properties or behavior from another existing type. Examples of good candidates for structures include:
- The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
- A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int. - A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.”
댓글 없음:
댓글 쓰기