Swift4 屬性,文檔代碼。
阿新 • • 發佈:2018-04-06
AMM function gin 屬性。 uri alt 詳細 pos current
屬性
蘋果官方文檔 Properties
蘋果官方文檔翻譯 屬性
屬性可以將值與特定的類、結構體或者是枚舉聯系起來。
存儲屬性
struct FixedLengthRange {
var firstValue: Int
let length: Int
}
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
rangeOfThreeItems.firstValue = 6
// the range now represents integer values 6, 7, and 8
常量結構體實例的儲存屬性
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==修飾語來表示一個延遲存儲屬性。且聲明必須為變量。
class DataImporter { //DataImporter is a class to import data from an external file. //The class is assumed to take a non-trivial 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 } let manager = DataManager() manager.data.append("Some data") manager.data.append("Some more data") // the DataImporter instance for the importer property has not yet been created
print(manager.importer.fileName)
// the DataImporter instance for the importer property has now been created
// prints "data.txt"
儲存屬性與實例變量
Swift 屬性沒有與之相對應的實例變量,並且屬性的後備存儲不能被直接訪問。
計算屬性
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)"
簡寫設置器(setter)聲明
如果一個計算屬性的設置器沒有為將要被設置的值定義一個名字,那麽他將被默認命名為 newValue 。
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)
}
}
}
只讀計算屬性
一個有讀取器但是沒有設置器的計算屬性就是所謂的只讀計算屬性。
去掉 get 關鍵字和他的大擴號來簡化只讀計算屬性的聲明:
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"
屬性觀察者
屬性觀察者會觀察並對屬性值的變化做出回應。
- willSet 會在該值被存儲之前被調用。
willSet 會在該值被存儲之前被調用。
class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 // About to set totalSteps to 200 // Added 200 steps stepCounter.totalSteps = 360 // About to set totalSteps to 360 // Added 160 steps stepCounter.totalSteps = 896 // About to set totalSteps to 896 // Added 536 steps
全局變量和局部變量
計算屬性和觀察屬性的能力同樣對全局變量和局部變量有效。
類型屬性
可以定義屬於類型本身的屬性,不是這個類型的某一個實例的屬性。這個屬性只有一個拷貝,無論你創建了多少個類對應的實例。這樣的屬性叫做類型屬性。
詳細參考文檔介紹。類型屬性語法
==static== 關鍵字來開一類型屬性
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 } }
查詢和設置類型屬性
類型屬性在類裏查詢和設置,而不是這個類型的實例。
print(SomeStructure.storedTypeProperty) // prints "Some value." SomeStructure.storedTypeProperty = "Another value." print(SomeStructure.storedTypeProperty) // prints "Another value." print(SomeEnumeration.computedTypeProperty) // prints "6" print(SomeClass.computedTypeProperty) // prints "27"
接下來的例子使用了兩個存儲類型屬性作為建模一個為數字音頻信道音頻測量表的結構體的一部分。每一個頻道都有一個介於 0 到 10 之間的數字音頻等級。
下邊的圖例展示了這個音頻頻道如何組合建模一個立體聲音頻測量表。當頻道的音頻電平為 0,那個對應頻道的燈就不會亮。當電平是 10 ,所有這個頻道的燈都會亮。在這個圖例裏,左聲道當前電平是 9 ,右聲道的當前電平是 7 :
struct AudioChannel {
static let thresholdLevel = 10
static var maxInputLevelForAllChannels = 0
var currentLevel: Int = 0 {
didSet {
if currentLevel > AudioChannel.thresholdLevel {
// cap the new audio level to the threshold level
currentLevel = AudioChannel.thresholdLevel
}
if currentLevel > AudioChannel.maxInputLevelForAllChannels {
// store this as the new overall maximum input level
AudioChannel.maxInputLevelForAllChannels = currentLevel
}
}
}
}
var leftChannel = AudioChannel()
var rightChannel = AudioChannel()
leftChannel.currentLevel = 7
print(leftChannel.currentLevel)
// prints "7"
print(AudioChannel.maxInputLevelForAllChannels)
// prints "7"
rightChannel.currentLevel = 11
print(rightChannel.currentLevel)
// prints "10"
print(AudioChannel.maxInputLevelForAllChannels)
// prints "10"
Swift4 屬性,文檔代碼。