기본적으로 사용되는 저장 프로퍼티(stored property)가 아닌
계산 프로퍼티(calculated property)에 대해 알아보겠습니다.
class의 용어정리 - https://chozjjae.tistory.com/43
class의 property와 method정리 - https://chozjjae.tistory.com/44
calculated property 란 ?
property가 설정되거나 검색되는 시점에서 계산 또는 파생 된 값을 의미합니다.
저장 프로퍼티(stored property) 예시코드
class hap{
var x : Int = 10
var y : Int = 20
init(x : Int, y: Int){
self.x = x
self.y = y
}
func math(){
print("값1 = \(x), 값2 = \(y)")
}
}
var cho : hap = hap(x:50,y:60)
cho.math()
var x : Int = 10
var y : Int = 20
계산 프로퍼티(calculated property) 예시코드
특징 1) 계산 프로퍼티에는 getter(게터)메서드와 setter(세터)메서드를 생성하여 구현합니다.
class hap{
var x : Int
var y : Int
var z : Int{
get{ return x + y}
set(age){
x = age + 50
}
}
init(x : Int, y: Int){
self.x = x
self.y = y
}
}
var cho : hap = hap(x:50,y:60)
//cho.math()
print(cho.z) //110
cho.z = 5
print(cho.x) //55
특징 2) setter메서드가 없을시 자동으로 getter메서드로 받아오기 때문에 getter 메서드는 생략 가능합니다.
특징1 소스와 비교하며, var z 부분 살펴보기
class hap{
var x : Int
var y : Int
var z : Int{
return x + y
}
init(x : Int, y: Int){
self.x = x
self.y = y
}
}
var cho : hap = hap(x:50,y:60)
//cho.math()
print(cho.z) //110
특징 3) setter에서 ( ) 안에 매개변수명을 기본 값 newValue로 한다면 ( )를 생략할 수 있다.
*특징1소스와 특징3소스를 비교했을때 한층 더 깔끔해진 소스
class hap{
var x : Int
var y : Int
var z : Int{
get{ return x + y }
set{ x = newValue + 50 }
}
init(x : Int, y: Int){
self.x = x
self.y = y
}
}
var cho : hap = hap(x:50,y:60)
//cho.math()
print(cho.z) //110
cho.z = 5
print(cho.x) //55
참고 자료 :
https://www.youtube.com/watch?v=u7pJTE-zkUU&list=PLJqaIeuL7nuEEROQDRcy4XxC9gU6SYYXb&index=27
'iOS_Swift > 문법 정리' 카테고리의 다른 글
Swift - Failable initializer (0) | 2022.02.08 |
---|---|
Swift - 클래스 생성자 중첩(method overloading) (0) | 2022.02.07 |
Swift - 클래스 init 메서드, self (0) | 2022.02.07 |
Swift - 클래스 instance생성 후 프로퍼티와 메서드 접근 (0) | 2022.02.06 |
Swift - 클래스 property와 method (0) | 2022.02.06 |