0
가 여기에 애플의 공식 가이드에서 예제 : 심지어 우리가 실제로 그들없이 할 수있는, 우리가/여기에서 설정 얻을 필요가 왜Swift에서 Computed Properties를 사용할 때 왜 get/set이 필요합니까? 실제로 그것들없이 코드를 작성할 수 있습니까?
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)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
println("square.origin is now at (\(square.origin.x), \(square.origin.y))")
// prints "square.origin is now at (10.0, 10.0)”
이 날 꽤 혼란하게, 나는 시도 :
struct anotherRect {
var origin = Point()
var size = Size()
var center: Point{
return Point(x: (origin.x + size.width/2), y: (origin.y + size.height/2))
}
}
var anotherSquare = Rect(origin: Point(x: 20.0, y: 20.0), size: Size(width: 10.0, height: 10.0))
println("anotherSquare.center is (\(anotherSquare.center.x), \(anotherSquare.center.y))")
// prints "anotherSquare.center is (25.0, 25.0)"
anotherSquare.center = Point(x: 30.0, y: 30.0)
println("anotherSquare.origin is now at (\(anotherSquare.origin.x), \(anotherSquare.origin.y))")
// prints "anotherSquare.origin is now at (25.0, 25.0)"
이를 통해 값을 얻거나 계산 된 속성에 새로운 값을 설정할 수 있습니다. Apple의 방식대로 정확히 동일하게 설정/가져올 수 있습니다. 우리 코드에서 실제로 설정해야합니까? 그리고 왜?
저는 신참 일 뿐이니이 모든 것에 대해 알려주세요. 나는 정말로 너의 도움을 appriciate !!
고마워요 @ 리카르도, 내 말이 맞습니다. 제 실수를 바꾸었고 코드가 당신이 말한 것과 정확히 일치합니다. * getter * 만 작동합니다. 감사!! – Shuyamaru
아무 문제없이 StackOverflow에 오신 것을 환영합니다. 질문에 대한 대답이 적절하다고 판단되면 받아 들일 수 있습니다 (녹색 체크 마크). 그렇게하면 수용된 대답에 응답 한 사람의 명성이 높아집니다. –
고맙습니다, 전 완전히 새로운 사람입니다. 그래서 저를 도우려는 사람에게 감사를 드리는 방법을 알지 못했지만 이제는 알았습니다. 다시 감사합니다!! – Shuyamaru