swift & iOS/swift

[swift] static 키워드: static이 붙은 프로퍼티와 메소드

whale3 2022. 2. 14. 22:53

아래 swift 공식 문서들을 읽고 정리한 내용임.

 

https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID264

 

Properties — The Swift Programming Language (Swift 5.6)

Properties Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value. Computed properties a

docs.swift.org

https://docs.swift.org/swift-book/LanguageGuide/Methods.html#ID241

 

Methods — The Swift Programming Language (Swift 5.6)

Methods Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for working with an instance of a given type. Classes, struc

docs.swift.org


'static'이 붙은 인스턴스 = type property

인스턴스를 만들어서 접근하는 프로퍼티는 인스턴스 마다 다른 값을 가지게 되는데(instance property), 이것 말고 타입 자체로 접근할 수 있는 프로퍼티를 만들려면 앞에 static 키워드를 붙이면 된다. 인스턴스가 몇 개가 있어도 static 이 붙은 프로퍼티는 타입 자체에만 연관된 것이며 오로지 static 그 자신, 딱 하나만 존재한다. (type property) 그래서 모든 인스턴스가 사용할 수 있는 값이 필요하거나 할 때 사용하면 된다. 

 

struct Game {
    static let somethingGlobal = true
    let life: Int
    let isGameOver = false
}

let firstGame = Game(life: 5)
firstGame.life
firstGame.isGameOver

let secondGame = Game(life: 3)
secondGame.life
secondGame.isGameOver

Game.somethingGlobal

 

위의 life, isGameOver 같은 stored instance property와 computed instance property가 있는 것처럼 'static' 키워드를 붙여 만드는 type property도 stored type property, computed type property가 있으며 stored type property는 var 또는 let으로 선언할 수 있지만 computed type property는 역시 var로만 선언할 수 있다. 다만 static 키워드가 붙은 stored type property는 위의 'somethingGlobal' 처럼 무조건 선언하면서 초기값도 같이 할당해야 한다.

 

type property에 대한 더 구체적인 예제가 공식 문서에 있어서 가져와봤다.

 

// 출처: https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID264

struct AudioChannel {
    static let thresholdLevel = 10
    static var maxInputLevelForAllChannels = 0
    
    // property observer
    var currentLevel: Int = 0 {
        didSet {
            if currentLevel > AudioChannel.thresholdLevel {
                // cap the new audio level to the threshold level
                currentLevel = AudioChannel.thresholdLevel
            }
            if currentLevel > AudioChannel.maxInputLevelForAllChannels {
                // store this as the new overall maximum input level
                AudioChannel.maxInputLevelForAllChannels = currentLevel
            }
        }
    }
}


var leftChannel = AudioChannel()
var rightChannel = AudioChannel()

leftChannel.currentLevel = 7
print(leftChannel.currentLevel)
// Prints "7"

print(AudioChannel.maxInputLevelForAllChannels)
// Prints "7"

rightChannel.currentLevel = 11
print(rightChannel.currentLevel)
// Prints "10"
print(AudioChannel.maxInputLevelForAllChannels)
// Prints "10"

 

 

'static'이 붙은 메소드 = type method

마찬가지로 instance method도 이름에서 알 수 있듯이 인스턴스를 통해 호출할 수 있는 함수다. 역시 'static' 키워드를 사용하여 인스턴스가 아닌 타입 그 자체로 호출하는 함수를 type method 라고 부른다. 다만 클래스에서는 static 키워드 대신에 'class' 키워드를 사용하여 type method를 작성할 수 있는데 이렇게 하면 자식 클래스가 이 type method를 오버라이딩 할 수 있다. ('static' 키워드가 붙은 type method는 자식 클래스도 오버라이딩 할 수 없음)

 

// 출처: https://docs.swift.org/swift-book/LanguageGuide/Methods.html#ID241
// 위에 나온 예제 활용

class SomeClass {
    class func someTypeMethod() {
        print("with class keyword")
    }
    
    static func otherTypeMethod() {
        print("with static keyword")
    }
}

class Child: SomeClass {
    override class func someTypeMethod() {
        print("i am Child!")
    }
}

Child.someTypeMethod() // "i am Child!"
Child.otherTypeMethod() // "with static keyword"

SomeClass.someTypeMethod() // "with class keyword"
SomeClass.otherTypeMethod() // "with static keyword"

 

반응형