- Properties
properties는 getter와 setter를 가진다.
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triagle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
perimeter속성에서 setter는 newValue라는 키워드로 값을 표현한다.
이것은 set후에 {}안에서 사용될 수 있다.
willSet, didSet을 사용하면 값을 설정하기 전이나 설정한 후에 원하는 추가 작업을 수행할
수 있다.
예1)
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
triangleAndSquare.triangle.sideLength
예2)
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
println("[willSet] 호출, 새로운 값: \(newTotalSteps)")
}
didSet {
println("[didSet] 호출")
if totalSteps > oldValue {
println("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
stepCounter.totalSteps = 360
stepCounter.totalSteps = 896
/*
[willSet] 호출, 새로운 값: 200
[didSet] 호출
Added 200 steps
[willSet] 호출, 새로운 값: 360
[didSet] 호출
Added 160 steps
[willSet] 호출, 새로운 값: 896
[didSet] 호출
Added 536 steps
*/
'Smart Device > Swift' 카테고리의 다른 글
Swift Enumerations (0) | 2014.06.29 |
---|---|
Swift Objects and Classes #3 (0) | 2014.06.29 |
Swift Numeric Types (0) | 2014.06.12 |
Swift Dictionary (0) | 2014.06.12 |
Swift Array #2 (0) | 2014.06.11 |