/**
(6)只读计算属性
对应 OC中的 readonly
*/
struct MyStudent {
var name: String
var chinese: Double
var math: Double
func showMySelf() -> Void {
print("姓名:\(name),语文成绩:\(chinese),数学成绩:\(math)")
}
}
class MyClass {
var members:[MyStudent] = []
var average: Double {
// 也可以省略 get函数
// get {
var t: Double = 0.0
for i in members {
t += i.chinese
t += i.math
}
if members.count > 0 {
return t / Double(members.count)
} else {
return 0
}
// }
}
func show() -> Void {
for i in members {
i.showMySelf()
}
}
}
let s0 = MyStudent.init(name: "zhangsan",chinese: 100.0,math: 100.0)
let s1 = MyStudent.init(name: "lisi",chinese: 90.0,math: 90.0)
let c0 = MyClass.init()
c0.members.append(s0)
c0.members.append(s1)
c0.show()
// 只读计算属性,我们看到给它赋值是不可以的
// c0.average = 900.0
print(c0.average)
原文链接:https://www.f2er.com/swift/322417.html