반응형
LinkedIn 개발자로 성장하면서 남긴 발자취들을 확인하실 수 있습니다.
Github WWDC Student Challenge 및 Cherish, Tiramisul 등 개발한 앱들의 코드를 확인하실 수 있습니다.
개인 앱 : Cherish 내 마음을 들여다보는 시간, 체리시는 디자이너와 PM과 함께 진행 중인 1인 개발 프로젝트입니다.
10년 후, 20년 후 나는 어떤 스토리 텔러가 되어 있을지 궁금하다. 내가 만약에 아직 조금 더 탐구하고 싶은 게 있고, 궁금한 게 있다면, 그게 설사 지금 당장의 내 인생에 도움이 안 되는 것 같더라도 경험해보자. 그 경험들을 온전히 즐기며 내 것으로 만들고, 내 일에 녹여내고... 그러다보면 그 점들이 모여 나란 사람을 그려내는 선이 될 테니까.

Recent Posts
Recent Comments
Total
관리 메뉴

꿈꾸는리버리

Property(1/4) - > StoredProperty 본문

오뚝이 개발자/swift

Property(1/4) - > StoredProperty

rriver2 2022. 4. 27. 19:03
반응형

Property란 class, struct, enum 에서 쓰이는 변수나 상수를 부르는 말이다.

+ ) 이 칭구들(class, struct, enum)에서 쓰이는 변수나 상수는 Property라고, 함수는 method라고 부른다. (특별 대우..,,)

 

Property에는 Stored Property, Computed Property, Type Property가 있다.

instance property stored instance property (var/let) + lazy stored property (var)
  computed instance property (var)  
type property stored type property (var/let) -> lazy  
  computed type property  (var)  

대략적인 표로 나타내면 위와 같은데 자세한 설명들은 앞으로의 포스팅에서 차례대로 설명할 예정이다.

 

 Stored Property 

그냥 일반적으로 작성해왔던 변수나 상수!! 

// ex )
struct 스트럭트명 {
	// storedProperty1: stored property (변수)
    var storedProperty1: Int 
    	// storedProperty2: stored property (상수)
    let storedProperty2: Int 
}

- let / var 둘 다 선언 가능

- struct , class 에서만 사용 가능 (enum X)

 

struct FixedLengthRange {
	// firstValue: stored property (변수)
    var firstValue: Int 
    	// length: stored property (상수)
    let length: Int 
}

var instance1 = FixedLengthRange(firstValue: 0, length: 3)
// firstValue = 0, length = 3
instance1.firstValue = 6
// firstValue = 6, length = 3
// length는 상수이므로 변경시 에러 발생

FixedLengthRange에는 2개의 stored property가 있다.

instance1라는 instance를 변수로 선언했고, instance1의 변수 property인 firstValue를 변경했다!

 

 struct와 class의 차이

💡struct는 값 참조

let instance2 = FixedLengthRange(firstValue: 0, length: 4)
instance2.firstValue = 6 // firstValue가 변수여도 에러 발생

instance2 인스턴스를 let으로 선언했기 때문에 FixedLengthRange의 property 중  var로 선언된 firstValue도 값을 변경할 수 없다.

<->💡class는 주소 참조

class FixedLengthRangeClass {
    var firstValue: Int // stored property (변수)
    let length: Int // stored property (상수)
    
    
    // class는 initialize 필수 !
    init( firstValue: Int, length: Int ){
        self.firstValue = firstValue
        self.length = length
    }
}

let instance3 = FixedLengthRangeClass(firstValue: 3, length: 4)
instance3.firstValue = 6

class는 인스턴스를 let으로 선언해도, class의 var인 property는 변경이 가능하다.

 

🔎 값 참조,, 주소 참조,,, 뭔 소리야 ...?

struct의 instance를 만들면, 스택에 struct의 프로퍼티의 "값"이 쌓인다. 이때 instance를 let으로 선언한다면 이 스택에 쌓인 "값"들이 변경을 하지 못하도록 lock 걸리게 된다.

 

반면에 class가 instance를 만들면, 스택에 해당 instance의 "주솟값"이 쌓인다. 이때 instance를 let으로 선언한다면 이 스택에 쌓인 "주솟값"이 변경을 하지 못하도록 lock 걸리게 된다. 그렇지만 주솟값은 lock이 걸려도 그 주솟값이 가리키고 있는 heap 영역에서의 property 값들중 var은 변경이 가능하게 된다.

 

 Lazy Stored Property 

나중에 property를 사용할 때 초기화되는 stored property

언제 사용 ?

- 초기화할 당시에 어떤 값을 넣어야 할지 모를때

: Human이라는 class에 이름, 나이 뿐만 아니라 출신지, 생일, 가족 관계 등등의 정보를 property로 저장하고 있는데 인스턴스를 만들때 당장 가족 관계 property의 내용을 넣을 수 없을 때

- 필요없는데 너무 많은 property가 초기화될 때

: 하나의 class를 선언 할 때 10000개의 property가 같이 초기화되고 그  property를 사용하지 않고 프로그램이 끝나버린다면 메모리 낭비가 심해진다. 이때 lazy로 선언하게 되면 10000개의 property는 호출되기 전까지 메모리에 올라가지 않는다.

// ex )
class 클래스명 {
    lazy var lazyStoredProperty : Int
}

 

- var 만 가능

: let은 반드시 초기화가 되기 전에 항상 값이 있어야 한다. 하지만 앞서 말한 대로 lazy stored property는 초기화가 된 이후 사용을 하게 될 때 값이 들어가기 때문에 let이 아닌 var을 사용해야 한다.

class DataImporter {
    /*
    DataImporter is a class to import data from an external file.
    The class is assumed to take a nontrivial amount of time to initialize.
    */
    var filename = "data.txt"
    // the DataImporter class would provide data importing functionality here
}

class DataManager {
    lazy var importer = DataImporter()
    var data: [String] = []
    // the DataManager class would provide data management functionality here
}

let manager = DataManager()
manager.data.append("Some data")
manager.data.append("Some more data")
// the DataImporter instance for the importer property hasn't yet been created

 

 

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

 

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

 

반응형

'오뚝이 개발자 > swift' 카테고리의 다른 글

removeLast() vs popLast()  (0) 2022.05.24
[2/2] optional chaining  (6) 2022.05.14
[1/2] Optional unwrapping  (0) 2022.05.14
Closure에서의 Capture ( feat . reference type) [2/3]  (4) 2022.05.11
Closure 넌 누구냐 ! [1/3]  (0) 2022.05.11
Comments