Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swift的存储属性和计算属性 #4

Open
miss-shiyi opened this issue Sep 29, 2021 · 0 comments
Open

swift的存储属性和计算属性 #4

miss-shiyi opened this issue Sep 29, 2021 · 0 comments
Labels
Swift Extra attention is needed

Comments

@miss-shiyi
Copy link
Owner

miss-shiyi commented Sep 29, 2021

1. 存储属性

2. 计算属性

除了存储属性,类、结构体和枚举也能够定义计算属性,而它实际并不存储值。相反,它提供
一个读取器和一个可选的设置器来间接得到和设置其它的属性和值。
如果一个计算属性的设置器没有为将要被设置的值定义一个名字,那么它将被默认命名为newValue
如果整个 getter 的函数体是一个单一的表达式,那么 getter 隐式返回这个表达式。

struct Point {
    var x = 0.0, y = 0.0
    
}

struct Size{
    var width = 0.0, height = 0.0
}

struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get{
//            let centerx = origin.x + size.width / 2
//            let centery = origin.y + size.height / 2
//            return Point(x: centerx, y: centery)
            return Point(x: origin.x + size.width / 2, y: origin.y + size.height / 2)
           //或者隐式返回 Point(x: origin.x + size.width / 2, y: origin.y + size.height / 2)
        }
//        set(newcenter){
//            origin.x = newcenter.x - size.width / 2
//            origin.y = newcenter.y - size.height / 2
//        }
        set{
            origin.x = newValue.x - size.width / 2
            origin.y = newValue.y - size.height / 2
        }
    }
}

var rect = Rect(origin: Point(x: 2, y: 4), size: Size(width: 4, height: 8))
print(rect.center)

rect.center = Point(x: 6, y: 9)
print(rect.origin.x)
@miss-shiyi miss-shiyi added the Swift Extra attention is needed label Sep 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Swift Extra attention is needed
Projects
No open projects
技术学习
Awaiting triage
Development

No branches or pull requests

1 participant