classHuman {
var carArr = ["宝马x1","大众CC","大众途观","奔驰GLA"]
//下标法
subscript(index:Int) ->String{
set{
carArr[index] = newValue
}
get{
returncarArr[index]
}
}
varname:String="" //默认的存储属性/读写属性
varheightM:Double=0.0{ //默认的存储属性/读写属性,属性监听
willSet{
print("之前身高:\(heightM)米,现在身高:\(newValue)米")
}
didSet{
print("确实长高了,之前\(oldValue)米,现在\(heightM)米")
}
}
varkind:String{ //只读属性
get{
return"哺乳动物"
}
}
varheightCM:Double{ //计算属性
set{
heightM= newValue /100
}
get{
returnheightM*100
}
}
init(name:String) {
self.name= name
}
convenienceinit(name:String,height:Double) {
self.init(name: name)
self.heightM= height
}
}
varh =Human(name:"胡歌", height:1.83)
h.heightM = 1.85
print(h.heightM)
print(h.heightCM)
h.heightCM = 185
print(h.heightM)
print(h.heightCM)
//h.kind = "动物" //因为kind是只读属性,不可以赋值
print(h.kind)
print(h.carArr[0])
print(h[0]) //因为提供了下标法,所以可以直接让对象使用下标0
h[0] = "宝马x3"
print(h.carArr[0])
print(h[0])
网友评论