计算属性,前面已经提到过一些.大致和 oc 中的 set 和get 方法差不多,读取和赋值等
//点
struct Point{
var x = 100
var y = 100
}
var point = Point()
print(point)
// 宽高
struct Size{
var width = 100
var height = 100
}
var size = Size()
print(size)
//区域
struct Rect{
var size = Size()
var origin = Point()
var center:Point{
// 只写 get 方法,就会是只读属性
get {
let x = rect.origin.x + rect.size.width/2
let y = rect.origin.y + rect.size.height/2
return Point(x: x,y: y )
}
//set 只是通过一种途径来修改属性的值
set(newValue) {
let x = newValue.x - size.width/2
let y = newValue.y - size.height/2
origin = Point(x: x,y:y)
}
}
}
var rect = Rect()
print(rect)
//求区域中心点
var p = Point(x: 100,y: 100)
var s = Size(width: 100,height: 100)
var r = Rect(size: s,origin: p)
print(r.center)
r.center = Point(x: 10,y: 10)
print(r.origin)
原文链接:https://www.f2er.com/swift/322650.html