有时候我们需要用同一个函数同时实现对变量的读(get)或者写(set)。这时会用到计算类型。
import Foundation
class Person {
var firstName = "Yun"
var lastName = "Long"
var fullName: String{
get{ // 读
return firstName + "." + lastName
}
set(newName){ // 写
var name = newName.componentsSeparatedByString(".")
// Returns an array containing substrings from the String that have been divided by a given separator.
firstName = name[0]
lastName = name[1]
}
}
}
var p = Person()
var xx = p.fullName
print("\(xx)")
// print Yun.Long
p.fullName = "Xiao.Hu";
var yy = p.fullName
print("\(yy)")
// print Xiao.Hu
var zz = p.firstName
print("\(zz)")
// print Xiao