티스토리 뷰

출처

http://kka7.tistory.com/15





프로퍼티 (Properties)

프로퍼티는 특정 클래스, 구조체, 열거형의 연관된 값이다.

저장 프로퍼티는 인스턴스의 일부로 
상수와 변수 값을 저장하는 반면
계산 프로퍼티는 값을 계산한다.

저장 프로퍼티는 클래스와 구조체에서만 제공되고
계산 프로퍼티는 클래스, 구조체, 열거형에서 제공된다.




저장 프로퍼티 (Stored Properties)

가장 단순한 형태로 상수나 변수에 저장된다.
var, let 키워드가 사용된다.

struct FixedLengthRange {

    var firstValue: Int

    let length: Int

}

var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)

// the range represents integer values 0, 1, and 2


rangeOfThreeItems.firstValue = 6



상수 구조체의 인스턴스 저장 프로퍼티

rangeOfThreeItems 이 상수 ( let ) 으로 정의되었기 때문에
firstValue 가 변수 프로퍼티라도 변경이 불가능하다.

let rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)

// the range represents integer values 0, 1, and 2


rangeOfThreeItems.firstValue = 6




느린 저장 프로퍼티 (Lazy Stored Properties)

처음 사용할 때까지 초기 값이 계산되지 않은 프로퍼티이다.

lazy 프로퍼티는 인스턴스 초기화가 완료될 때까지 
초기 값을 가져올 수 없기 때문에 항상 var 로 선언해야한다.

상수 프로퍼티는 항상 초기화가 완료되기 전에 값을 가지고 있어야하므로
lazy 로 선언될 수 없다.

아래예제에서 importer 프로퍼티를 처음으로 접근할 때
생성된다.

class DataImporter {

    var fileName = "data.txt"

}


class DataManager {

    lazy var importer = DataImporter()

    var data = [String]()

}


let manager = DataManager()

manager.data.append("Some data")

manager.data.append("Some more data")


print(manager.importer.fileName)




계산 프로퍼티 (Computed Properties)

프로퍼티, 클래스, 구조체와 열거형을 저장하기 위해

실제 값을 저장하지는 않는 계산 프로퍼티를 정의할 수 있다.


대신, 다른 프로퍼티와 값을 직접 가져오고 설정하기 위해

getter 와 setter 를 제공한다.


struct Point { var x = 0.0, y = 0.0 }

struct Size { var width = 0.0, height = 0.0 }


struct Rect {

    var origin = Point()

    var size = Size()

    var center: Point {

        get {

            let centerX = origin.x + (size.width / 2)

            let centerY = origin.y + (size.height / 2)

            return Point(x: centerX, y: centerY)

        } set(newCenter) {

            origin.x = newCenter.x - (size.width / 2)

            origin.y = newCenter.y - (size.height / 2)

        }

    }

}


var square = Rect(origin: Point(x: 0.0, y: 0.0),

                  size: Size(width: 10.0, height: 10.0))


let initialSquareCenter = square.center


square.center = Point(x: 15.0, y: 15.0)

print("square.origin is now at (\(square.origin.x), \(square.origin.y))")

// 10, 10



축약된 Setter 선언

새로운 값에 대한 이름을 정의하지 않는 경우
기본적으로 newValue 이름이 사용된다.

struct AlternativeRect {

    var origin = Point()

    var size = Size()

    var center: Point {

        get {

            let centerX = origin.x + (size.width / 2)

            let centerY = origin.y + (size.height / 2)

            return Point(x: centerX, y: centerY)

        }

        set {

            origin.x = newValue.x - (size.width / 2)

            origin.y = newValue.y - (size.height / 2)

        }

    }

}



읽기 전용 계산 프로퍼티 (read-only)

setter 가 없이 getter 만 가진 계산 프로퍼티는

read only 속성을 가지게 된다.


계산 프로퍼티 (읽기 전용 계산 프로퍼티 포함) 는 값이 고정되어있지 않기 때문에

var 키워드로 변수 프로퍼티로 선언해야한다.


struct Cuboid {

    var width = 0.0, height = 0.0, depth = 0.0

    var volume: Double {

        return width * height * depth

    }

}


let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)

print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")





프로퍼티 옵저버

willSet 은 값이 저장되기 직전에 호출된다.
didSet 은 새로운 값이 저장된 직후에 호출된다.

willSet 도 동일하게 파라미터 이름을 지정하지 않으면
newValue 로 참조할 수 있다.
didSet 은 oldValue 로 참조할 수 있다.

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




전역변수와 지역변수

전역 변수는 모든 함수, 메솓, 클로저, 타입 context 밖에 정의된 변수이다.
지역 변수는 함수, 메소드, 클로저 context 안에 정의된다.

전역 상수와 변수는 lazy 저장 프로퍼티와 유사한 방식으로
항상 나중에 계산된다. (lazy)
lazy 저장 프로퍼티와 다르게 전역 상수와 변수는 lazy 표시할 필요가 없다.

반면, 지역 상수와 변수는 절대로 나중에 계산되지 않는다.






타입 프로퍼티 (Type Property Syntax)

static 키워드로 타입 프로퍼티를 정의한다.
클래스 타입에 대해 계산 타입 프로퍼티는 

상위 클래스의 구현을 오버라이드하는 하위클래스를 허용하는 대신
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

    }

}


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()


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"






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

[Swift 3] 서브스크립트 (Subscript)  (0) 2017.04.15
[Swift 3] 메소드 (Method)  (0) 2017.04.15
[Swift 3] 클래스와 구조체  (1) 2017.04.14
[Swift 3] 열거형 (Enumerations)  (0) 2017.04.14
[Swift 3] 클로저 (Closures)  (0) 2017.04.14
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함