枚举也具有属性和方法,这在c++中是不可想象的。
例如:
enum Device {
case iPad, iPhone, AppleTV, AppleWatch
func introduced() -> String {
switch self {
case .AppleTV:
return "\(self) was introduced 2006"
case .iPhone:
return "\(self) was introduced 2007"
case .iPad:
return "\(self) was introduced 2010"
case .AppleWatch:
return "\(self) was introduced 2014"
}
}
}
print(Device.AppleTV.introduced())
enum Device2 {
case iPad, iPhone
var year: Int {
switch self {
case .iPhone:
return 2007
case .iPad:
return 2010
}
}
}
print(Device2.iPad.year)
另外,swift中将属性分成存储属性和计算属性,其中存储属性与c++相同(枚举只有计算属性,没有存储属性,结构体和类才有存储睡醒)。
swift的计算属性语法:
var property:propertyType {
get {
}
set {
}
}
这与c++类定义一个成员变量,再定义setter和getter类似,只是讲以上方法都归在计算属性里了。
属性观察器
swift的属性观察器语法如下:
class StepCounter {
var totalSteps: Int = 0 {
willSet {
print("About to set totalSteps to \(newValue)")
}
didSet {
print("Added \(totalSteps - oldValue) steps")
}
}
}
let stepA = StepCounter()
stepA.totalSteps = 200
let stepB = stepA
stepB.totalSteps = 300
print(stepA.totalSteps)
属性观察器用于监控和响应属性的变化,c++有一些观察机制,但概念与此相去甚远。
swift的类型属性和类型方法与c++的静态成员和静态方法相似,
也是要加前缀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
}
}