Properties

  1. Stored Properties
  2. Computed Properties
  3. Property Observers
  4. Global and Local Variables
  5. Type Properties

Properties

1. Stored Properties

  • A stored property is a constant or variable that is stored as part of an instance of a particular class or structure. 
  • Default property values
  • Assiging Constant properties during initalization (초기화 중에 할당되는 프로퍼티)

1-1) 상수 Structure 인스턴스의 stored property

  • If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties:
let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)
// this range represents integer values 0, 1, 2, and 3
rangeOfFourItems.firstValue = 6 // this will report an error, even though firstValue is a variable property
  • 결론)
    Value type의 인스턴스를 상수로 생성하면, 모든 property는 변경할 수 없다.
    반대로, Reference type의 인스턴스를 constant로 생성하면 변경 가능하다.

1-2) Lazy Stored Properties:  인스턴스 초기화 -> 값 계산 -> 값 세팅

  • lazy stored property: 최초 사용될 때까지 초기 값이 계산되지 않는 프로퍼티
  • var keyword를 사용해야 함 => lazy stored property는 인스턴스 초기화가 완료될 때 까지 초기값을 가져올 수 없으므로 
    (let: 초기화가 완료되기 전에 값을 가져야 함.)

 

2. Computed Properties

  • Class, structure, enumeration은 computed property 정의 가능
  • 실제로 값을 저장하는 것이 아님
  • getter와 optional setter를 제공하여 다른 property의 값을 간접적으로 세팅할 수 있다.
struct CompactRect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            Point(x: origin.x + (size.width / 2),
                  y: origin.y + (size.height / 2))
        }
        set {
            origin.x = newValue.x - (size.width / 2)
            origin.y = newValue.y - (size.height / 2)
        }
    }
}

 

3. Property Observers

  • property observer는 property의 값의 변화에 관찰하고 반응한다!(observe and respond)
  • property의 값이 세팅되는 매 순간마다 호출됨. (같은 값으로 세팅되더라도)
  • lazy stored property를 제외한 모든 property(stored, computed property)에 추가 가능
  • overriding된 상속받은 property에도 property observer를 추가할 수 있다.
  • observer 종류
    - willSet is called just before the value is stored.
    - didSet is called immediately after the new value is stored.
  • in-out 으로 observer를 가지는 property가 parameter로 전달되어도, willSet과 didSet observer는 항상 호출됨.
    => copy-in copy-out memory model이기 때문에!
class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("About to set totalSteps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added \(totalSteps - oldValue) steps")
            }
        }
    }
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
// About to set totalSteps to 200
// Added 200 steps
stepCounter.totalSteps = 360
// About to set totalSteps to 360
// Added 160 steps
stepCounter.totalSteps = 896
// About to set totalSteps to 896
// Added 536 steps

 

 

4. Global and Local Variables

  • Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties.
    Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.

  • Local constants and variables are never computed lazily.

 

5. Type Properties

  • 클래스 변수
  • static keyword로 정의
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()

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"

 

 

 

 

Ref.

https://kka7.tistory.com/116?category=919617

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

'iOS > Swift' 카테고리의 다른 글

[Swift 5.2] Methods - Apple Documentation  (0) 2020.03.05
[Swift] ExpressibleByStringLiteral, CustomStringConvertible  (0) 2020.02.18
[Swift4.1] map, flapMap, compactMap  (0) 2019.12.11
[Swift5.1] Overview  (0) 2019.12.04
[Swift] if let vs. guard let  (0) 2019.11.29

+ Recent posts