blog
blog copied to clipboard
swift4 语法备忘 - Properties
Properties
Properties
associate values with a particular class, structure, or enumeration.
-
Computed properties are provided by classes, structures, and enumerations. Stored properties are provided only by classes and structures.
-
Stored and computed properties are usually associated with instances of a particular type.
-
Properties can also be associated with the type itself. Such properties are known as
type properties
. -
Define property observers to monitor changes in a property’s value
Stored Properties
stored property
is aconstant
orvariable
that is stored as part of an instance of a particular class or structure. Stored properties can be introduced by thevar
orlet
keywordDefault value can be provided for a stored property as part of its definition
struct FixedLengthRange {
var firstValue: Int
let length: Int
}
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
// the range represents integer values 0, 1, and 2
rangeOfThreeItems.firstValue = 6
// the range now represents integer values 6, 7, and 8
Stored Properties of Constant Structure Instances
If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties:
let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)
// this range represents integer values 0, 1, 2, and 3
rangeOfFourItems.firstValue = 6
// this will report an error, even though firstValue is a variable property
Lazy Stored Properties
A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.
class DataImporter {
/*
DataImporter is a class to import data from an external file.
The class is assumed to take a nontrivial amount of time to initialize.
*/
var filename = "data.txt"
// the DataImporter class would provide data importing functionality here
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()
// the DataManager class would provide data management functionality here
}
print(manager.importer.filename)
// the DataImporter instance for the importer property has now been created
// Prints "data.txt"
Computed Properties
Computed properties
which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
print("square.origin is now at (\(square.origin.x), \(square.origin.y))")
// Prints "square.origin is now at (10.0, 10.0)"
Shorthand Setter Declaration
computed property’s setter does not define a name for the new value to be set, a default name of
newValue
is used.
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
Read-Only Computed Properties
A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double {
return width * height * depth
}
}
let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
// Prints "the volume of fourByFiveByTwo is 40.0"
Property Observers
Property observers
observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.
option to define either or both of these observers on a property:
-
willSet
is called just before the value is stored. -
didSet
is called immediately after the new value is stored.
If you implement a
willSet
observer, it’s passed the new property value as a constant parameter. You can specify a name for this parameter as part of your willSet implementation.
If you don’t write the parameter name and parentheses within your implementation, the parameter is made available with a default parameter name of
newValue
.
If you implement a
didSet
observer, it’s passed a constant parameter containing the old property value. You can name the parameter or use the default parameter name ofoldValue
. If you assign a value to a property within its owndidSet
observer, the new value that you assign replaces the one that was just set.
Type Properties
Instance properties are properties that belong to an instance of a particular type. Every time you create a new instance of that type, it has its own set of property values, separate from any other instance.
Type Property Syntax
You define type properties with the
static
keyword. For computed type properties for class types, use theclass
keyword instead to allow subclasses to override the superclass’s implementation.
struct SomeStructure {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 1
}
}
enum SomeEnumeration {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 6
}
}
class SomeClass {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 27
}
class var overrideableComputedTypeProperty: Int {
return 107
}
}