programming/Swift
[Swift/iOS] 인스턴스 메소드와 타입메소드, static 메소드와 class 메소드
마들브라더
2022. 10. 25. 18:22
인스턴스 메소드와 타입메소드, static 메소드와 class 메소드
- 인스턴스 메소드 - 특정 타입의 ‘인스턴스’에서 호출
- 타입 메소드 - ‘특정 타입 자체’에서 호출
- func 앞에 static 또는 class 키워드를 추가해서 선언
- static 메소드와 class 메소드의 차이
- static
- 서브클래스에서 오버라이드 할 수 없음
- class
- 서브클래스에서 오버라이드 할 수 있음
- static
메소드의 호출
- 똑같이 점(.)문법으로 호출 할 수 있음
- 다만, 인스턴스에서 호출하는 것이 아니라 타입에서 호출함
class SomeClass {
class func someTypeMethod() {
// 타입 메소드 구현
}
}
SomeClass.someTypeMethod() // 메소드 호출
타입 메소드 안의 ‘self’
- 타입 메소드 안에서도 ‘self’ 키워드를 사용할 수 있음
- 타입 메소드 안에서의 ‘self’는 인스턴스가 아닌 타입 자신을 의미
- 타입 메소드 안에서 다른 타입메소드 사용할 수 있음
class SomeClass {
class func someTypeMethod() {
// 타입 메소드 구현
}
}
SomeClass.someTypeMethod() // 메소드 호출
struct LevelTracker {
static var highestUnlockedLevel = 1
var currentLevel = 1
static func unlock(_ level: Int) {
if level > highestUnlockedLevel {
highestUnlockedLevel = level
}
}
static func isUnlocked(_ level: Int) -> Bool {
return level <= highestUnlockedLevel
}
// @discardableResult
mutating func advance(to level: Int) -> Bool {
if LevelTracker.isUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}
class Player {
var tracker = LevelTracker()
let playerName: String
func complete(level: Int) {
LevelTracker.unlock(level + 1) // 1 들어오면 highest level 2로 만듦
tracker.advance(to: level + 1) // 1 들어오면 current Level을 2로 만듦
}
init(name: String) {
playerName = name
}
}
var player = Player(name: "Argyrios") // 인스턴스 생성
player.complete(level: 1) // 1단계 성공
print("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)") // "highest unlocked level is now 2"
player = Player(name: "Beto")
if player.tracker.advance(to: 6) {
print("player is now on level 6")
} else {
print("level 6 has not yet been unlocked")
}
// "level 6 has not yet been unlocked" 출력