공부/SWIFT

[SWIFT] 프로퍼티(타입 프로퍼티) ★★★

알로하리미 2021. 3. 11. 17:21
728x90

1. 개요

키워드 static, class 을 사용

타입 프로퍼티는 특정 타입에 속한 프로퍼티로
그 타입에 해당하는 단 하나의 프로퍼티만 생성됩니다.

이 타입 프로퍼티는 특정 타입의 모든 인스턴스에
공통으로 사용되는 값을 정의할때 유용합니다.
타입 이름 만으로 프로퍼티를 사용 할 수 있다.  Class.typeProperties

인스턴스 프로퍼티와는 다르게 타입 프로퍼티는 항상 초기값을 지정해서 사용해야 합니다.
왜냐하면 타입 자체에는 초기자(생성자, Initializer)가 없어 초기화 할 곳이 없기 때문입니다.

구조체에선 static만 사용

클래스에서는 staticclass 이렇게 2가지 형태로 타입 프로퍼티를 선언할 수 있는데
두 가지 경우의 차이는 서브클래스에서
overriding가능 여부이다.
class로 선언된 프로퍼티는 서브클래스에서 오버라이드 가능합니다

* 부모(수퍼클래스)의 것을 자식(서브클래스)가 재정의 하는것

struct SomeStructure {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        return 1
    }
}

enum SomeEnumeration {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        return 6
    }
}

class SomeClass {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        return 27
    }
    class var overrideableComputedTypeProperty: Int {
        return 107
    }
}

 

 

타입 프로퍼티도 점연산자(dot operator)로 프로퍼티의 값을 가져오고 할당할 수 있습니다

print(SomeStructure.storedTypeProperty)
// Prints "Some value."

SomeStructure.storedTypeProperty = "Another value."
print(SomeStructure.storedTypeProperty)
// Prints "Another value."

print(SomeEnumeration.computedTypeProperty)
// Prints "6"

print(SomeClass.computedTypeProperty)
// Prints "27"

 

 

오디오 채널 볼륨

다음 예제 코드는 오디오 채널의 볼륨을 조절하고 관리하는 구조체 입니다.

struct AudioChannel {
 
    // 고정된 볼륨 최대 레벨 값
    static let thresholdLevel = 10
    
    // 지금까지 최대 볼륨 레벨
    static var maxInputLevelForAllChannels = 0 
    
    // 입력 볼륨 크기
    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()


// 좌 채널 현재 레벨 7 입력
leftChannel.currentLevel = 7
print(leftChannel.currentLevel)
// Prints "7"
print(AudioChannel.maxInputLevelForAllChannels)
// Prints "7"


// 우 채널 11 입력
rightChannel.currentLevel = 11
print(rightChannel.currentLevel) //didSet에서 10 넘지 못하게 막음.
// Prints "10"
print(AudioChannel.maxInputLevelForAllChannels)
// Prints "10"

 

 

* 키 경로

키 경로를 잘사용하면 프로토콜과 마찬가지로 타입간의 의존성을 낮추는데 많은 도움이 됨.

//특정 타입의 프로퍼티의 위치를 참조하도록 할수 있다.

\타입이름.경로.경로.경로

let keyPath = \ClassName.propertyName
let pathAdd = keyPath.appending(path: \.name)
class Person {
    let name: String
    init(name: String) {
        self.name = name
    }
}


struct Stuff {
    var name: String
    var owner: Person
}


//상수로 지정된 참조타입의 프로퍼티 var는 변경가능 let변경 불가
let aloha = Person(name: "알로하리미") 
let hana = Person(name: "하나")

//상수로 지정한 값타입 변경 불가. 안에 프로퍼티가 var라도 변경 불가.
let note = Stuff(name: "연습장" , owner: aloha) 
let book = Stuff(name: "주식책", owner: hana)  

//변수로 지정한 값타입 변경 가능.
var phone = Stuff(name: "아이폰", owner: aloha)


let stuffNameKeyPath = \Stuff.name
let ownerKeyPath = \Stuff.owner
let ownerNameKeyPath = ownerKeyPath.appending(path: \.name)

// 키경로와 서브스키릅트를 이용해 프로퍼티에 접근 가능
print( note[keyPath: stuffNameKeyPath] ) //연습장
print( phone[keyPath: stuffNameKeyPath] )//아이폰
print( bookp[keyPath: \Stuff.name] ) //주식책

print( note[keyPath: ownerNameKeyPath] ) //알로하리미
print( phone[keyPath: ownerNameKeyPath] ) //알로하리미
print( book[keyPath: ownerNameKeyPath] ) //하나

// 키경로와 서브스크립트를 이용해 프로퍼티에 할당 가능
phone[keyPath: stuffNameKeyPath] = "아이폰 12 프로"
phone[keyPaht: ownerKeyPath] = hana

print( phone[keyPath: stuffNameKeyPath] ) // 아이폰 12 프로
print( phone[keyPath: ownerNameKeyPath] ) // 하나


 

 

 

2021.03.11 - [공부/SWIFT] - [SWIFT] 프로퍼티( 저장 프로퍼티 ) ★★★

2021.03.11 - [공부/SWIFT] - [SWIFT] 프로퍼티( 연산 프로퍼티 ) ★★★

2021.03.11 - [공부/SWIFT] - [SWIFT] 프로퍼티( 프로퍼티 옵저버 ) ★★★