Created
January 22, 2018 04:09
-
-
Save sooop/38eb50c9330a25fd5f3794e5db1e1010 to your computer and use it in GitHub Desktop.
Swift 클래스의 프로퍼티와 상속 예제
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
//: ## 1 : 클래스의 프로퍼티 정의방법 | |
class Foo { | |
/// 일반적인 stored property | |
var a: Int = 4 | |
/// stored property + observer methods | |
var b: Int = 10 { | |
willSet { | |
print("[Foo] Property b will change: \(b) -> \(newValue)") | |
} | |
didSet { | |
print("[Foo] Property b has been changed: \(b)") | |
} | |
} | |
/// computed Property | |
var c: Int { | |
return a + b | |
} | |
/// computed property with setter | |
var d: Int { | |
get { | |
return a + b | |
} | |
set(v) { | |
// b + a (a는 한자리 정수)의 형태로 분해하여 저장함 | |
let p = v % 10 | |
b = v - p | |
} | |
} | |
} | |
let f = Foo() | |
f.a = 6 | |
print(f.c) // 16 | |
f.b = 20 // call observers | |
print(f.c) // 26 | |
f.d = 52 | |
print(f.a, f.b) | |
//: 2 : Foo를 상속하기 | |
class Bar: Foo { | |
/// stored property였던 a를 computed property로 오버라이드 | |
/// 부모 클래스의 getter/setter를 이용해서 부모클래스보다 10배로 불어난 | |
/// 값을 취급하도록 한다. | |
override var a: Int { | |
get { | |
return super.a * 10 | |
} | |
set { | |
super.a = newValue / 10 | |
} | |
} | |
override var b: Int { | |
willSet { | |
print("[Bar] property b will be changed.") | |
} | |
didSet { | |
print("[Bar] property b has been changed.") | |
} | |
/* | |
[Bar] property b will be changed. | |
[Foo] Property b will change: 30 -> 204 | |
[Foo] Property b has been changed: 204 | |
[Bar] property b has been changed. | |
254 254 | |
*/ | |
} | |
override var d: Int { | |
/// setter를 오버라이드하기 위해서는 | |
/// getter를 반드시 오버라이드해야 한다. | |
get { | |
return super.d | |
// super.d 는 return a + b인데, | |
// 이 값은 self에 대해서 수행된다. | |
// 따라서 d는 204 + 5(*10) 으로 254가 리턴될 것이다. | |
} | |
set { | |
a = newValue % 100 | |
// newValue가 254이면 a에는 54가 들어가지만 | |
// setter에 의해서 실제로는 5가 저장되고 50으로 액세스된다. | |
// 아래 표현식에서 a는 현재 클래스의 a 접근자를 사용한다. | |
// 따라서 254 - 50 이 처리되어 b = 204가 된다. | |
b = newValue - a | |
} | |
} | |
} | |
let b = Bar() | |
b.b = 30 // Bar, Foo의 옵저버가 순차적으로 실행된다. | |
b.a = 80 // 실제로 저장되는 값은 8이된다. | |
// 하지만 저장된 값을 *10 해서 액세스하므로 아래 두 출력에서는 80으로 취급된다. | |
print(b.a, b.d) | |
b.a = 84 | |
// 이 경우는 위와 동일하게 8이 저장되고, 84로 액세스된다. | |
print(b.a, b.d) | |
b.d = 254 | |
// 254는 200 + 54 가 되는데 a는 54/10 => 5가 저장되고 | |
// b는 254 - a 일 때, a의 getter는 5 * 10이므로 204가 저장된다. | |
// 따라서 b.d는 204 + 50 으로 254가 저장될 것이다. | |
print(b.a, b.b, b.d) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment