공부한 것 꼭꼭 씹어먹기

property 본문

Swift 기초

property

젤라솜 2021. 10. 26. 20:42
반응형

저장 프로퍼티 : 인스턴스의 프로퍼티에 값을 저장하는 것

struct Dog() {
	var name: String
	let gender: String
}

var dog = Dog(name: "gunter", gender: "male")
dog.name = "Eun"
dog.gender = "female" // ❌ 상수라서 값 재할당 불가

let dog2 = Dog(name: "gunter", gender: "male")
dog2.name = "Eun" // ❌ name은 var지만 dog2를 let으로 선언했기때문에 내부 프로퍼티도 다 변경불가함

class Cat() {
	var name: String
	let gender: String
	init(name: String, gender: String) {
		self.name = name
		self.gender = gender
	}
}

let cat = Cat(name: "json", gender: "male")
cat.name = "Eun" // 재할당 가능. 물론 gender는 let으로 선언했기때문에 재할당 불가.

// 구조체는 value type이고 클래스는 reference type이라서 상수로 인스턴스를 만들었어도 재할당 가능

 

연산 프로퍼티 : 계산이 들어가는 프로퍼티 (여기서는 purchasePrice)

struct Stock {
	var averagePrice: Int
	var quantity: Int
	var purchasePrice: int {
		get {
			return averagePrice * quantity
		}
		set(newPrice) {
			averagePrice = newPrice / quantity
		} 
	}
}

var stock = Stock(averagePrice: 2300, quantity: 3)
stock.purchasePrice // 6900출력. get()을 통해 purchasePrice가 계산됨
stock.purchasePrice = 3000  // set()을 통해 averaePrice가 다시 계산됨
stock.averagePrice // 1000출력. 

// TIP //
// 연산 프로퍼티에 set 메서드를 선언하지 않으면 읽기 전용으로 쓸 수 있음
// set메서드에 매개변수 없이 기본변수인 newValue를 써도 됨.(newValue라는 키워드를 자동으로 인지하나봄)
// set { averagePrice = newValue / quantity }

// 프로퍼티 옵저버 : 프로퍼티 값의 변화를 감지한다.
class Account {
	var credit: Int = 0 {
		//소괄호 이름 지정
		willSet { 
			print("잔액이 \(credit)원에서 \(newValue)원으로 변경될 예정입니다.")
		}
		didSet {
			print("잔액이 \(oldValue)원에서 \(credit)원으로 변경되었습니다.")
		}
	}
}
var account = Account()
account.credit = 1000
// 잔액이 0원에서 1000원으로 변경될 예정입니다. 
// 잔액이 0원에서 1000원으로 변경되었습니다.

 

타입 프로퍼티 : 인스턴스 생성 없이 객체내의 프로퍼티에 접근 가능함. ( Static 같은것이다)

struct SomeStructure {
	static var storedTypeProperty = "Some value"  
}
SomeStructure.storedTypeProperty = "other value" // 값 재할당 가능
반응형

'Swift 기초' 카테고리의 다른 글

타입캐스팅 : is, as  (0) 2021.10.28
상속  (0) 2021.10.27
class, struct, enum  (0) 2021.10.25
함수  (0) 2021.10.24
optional  (0) 2021.10.24
Comments