Open Suyeon9911 opened 2 years ago
// 클래스의 인스턴스 메서드
class LevelClass {
// 현재 레벨을 저장하는 저장 프로퍼티
var level: Int = 0 {
// 프로퍼티 값이 변경되면 호출하는 프로퍼티 감시자
didSet {
print(level)
}
}
// 레벨이 올랐을 때 호출하 ㄹ메서드
func levelUp() {
level += 1
}
// 레벨이 감소할 때 호출할 메서드
func levelDown() {
level -= 1
if level < 0 {
reset()
}
}
// 특정 레벨로 이동할 때 호출할 메서드
func jumpLevel(to: Int) {
level = to
}
// 레벨을 초기화할 때 호출할 메서드
func reset() {
level = 0
}
}
var levelClassInstance: LevelClass = LevelClass()
levelClassInstance.levelUp()
모든 인스턴스는 암시적으로 생성된 self 프로퍼티를 갖는다.
자바의 this와 비슷하게 인스턴스 자기 자신을 가리키는 프로퍼티
self 프로퍼티는 인스턴스를 더 명확히 지칭하고 싶을 때 사용합니다.
level 변수를 사용할 때, 스위프트는 자동으로 메서드 내부에 선언된 지역변수를 먼저 사용하고, 그다음에 메서드 매개변수, 그다음 인스턴스의 프로퍼티를 찾아서 level 이 무엇을 지칭하는지 유추.
그런데 메서드 매개변수의 이름이 level인데 이 level 매개변수가 아닌 인스턴스 프로퍼티인 level을 지칭하고 싶다면 self 프로퍼티 사용 ! !
즉 메서드 안에서 level = level이라고 하면 컴파일러는 메서드의 매개변수로 넘어온 level을 지칭하는 것으로 판단, 하지만 self.level이라고 해주면 인스턴스 프로퍼티란느 것을 명확히 할수 있음.
또, self 프로퍼티의 다른 용도는 값 타입 인스턴스 자체의 값을 치환할 수 있다.
클래스의 인스턴스는 참조 타입이라서 self 프로퍼티에 다른 참조를 할당할 수 없는데, 구조체나 열거형 등은 self 프로퍼티를 사용하여 자신 자체를 치환할 수 있음 !!
class LevelClass {
var level: Int = 0
func reset() {
// 오류 !
self = LevelClass()
}
}
struct LevelStruct {
var level: Int = 0
mutating func levelUp() {
level += 1
}
mutating func reset() {
self = LevelStruct()
}
}
enum OnOffSwitch {
case on, off
mutating func nextState() {
self = self == .on ? .off : .on
}
}
var toggle: OnOffSwitch = OnOffSwitch.off
toggle.nextState()
print(toggle) // on
struct Puppy {
var name: String = "흰둥이"
func callAsFunction() {
print("멍멍")
}
func callAsFunction(destination: String) {
print("\(destination)으로 달려갑니다.")
}
}
var myPuppy: Puppy = Puppy()
myPuppy.callAsFunction()
myPuppy()
myPuppy.callAsFunction(destination: "집")
myPuppy(destination: "집")
class AClass {
static func staticTypeMethod() {
print("에이 클래스 타입메서드")
}
class func classTypeMethod() {
print("에이 클래스 클래스 메서드")
}
}
class BClass: AClass {
override class func classTypeMethod() {
print("비 클래스 클래스 메서드")
}
// 타입메서드는 재정의 불가능
}
AClass.staticTypeMethod() // 에이 클래스 타입메서드
AClass.classTypeMethod() // 에이 클래스 클래스 메서드
BClass.classTypeMethod() // 비 클래스 클래스 메서드
// 시스템 용량은 함 기기에서 유일한 값
struct SystemVolume {
// 타입프로퍼티를 사용하면 언제나 유일한 값이 된다.
static var volume: Int = 5
// 타입프로퍼티를 제어하기 위해 타입 메서드를 사용
static func mute() {
self.volume = 0 // SystemVolume.volume 과 같은 표현, Self.volume과도 같은표현
}
}
// 내비게이션 역할은 여러 인스턴스가 수행할 수 있다.
class Navigation {
// 내비게이션 인스턴스마다 음량을 따로 설정할 수 있다.
var volume: Int = 5
// 길 안내 음성 재생
func guideWay() {
// 내비게이션 외 다른 재생원 음소거
SystemVolume.mute()
}
// 길 안내 음성 종료
func finishGuideWay() {
// 기존 재생원 음서 ㅇ복구
SystemVolume.volume = self.volume
}
}
SystemVolume.volume = 10
let myNavi: Navigation = Navigation()
myNavi.guideWay()
print(SystemVolume.volume) // 0
myNavi.finishGuideWay()
print(SystemVolume.volume) // 5
[Swift] static과 class method, property 효과적으로 사용하기 [Swift] class func vs static func
읽어보면 좋을듯... 수진꽐,, 보곺다..
Swift 의 Method 에 관한 총 정리