→ 값을 ‘저장’한다기보다는 특정한 연산을 통해서 값을 리턴해준다!
예)
class Point {
var tempX : Int = 1
var x: Int {
get {
return tempX
}
set(newValue) {
tempX = newValue * 2
}
}
}
var p: Point = Point()
p.x = 12
set(newValue) {
tempX = newValue * 2
}
set(miro) {
tempX = miro * 2
}
set {
tempX = newValue * 2
}
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)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
// Rectangel instance 생성하기
var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))
// get이 발동이된다! -> square.center 값이 무엇인지 연산만 해준거다!
let initialSquareCenter = square.center
print(initialSquareCenter) //(x: 5.0,y: 5.0)
// set이 발동이된다. 새로운 값으로 설정해주는 것이다.
square.center = Point(x: 15.0, y: 15.0)
print("square.origin is now at (\(square.origin.x), \(square.origin.y))")
// Prints "square.origin is now at (10.0, 10.0)"
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)
}
// 괄호를 없애고 newValue로 해준다!
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double {
return width * height * depth
}
}