이번 글은 프로퍼티와 메소드에 대해 작성하고자 한다.
저장 프로퍼티
연산 프로퍼티
타입 프로퍼티
프로퍼티 감시자(옵저버)
var westernAge: int {
get {
return koreanAge - 1
}
set(inputValue) {
koreanAge = inputValue + 1
}
}
//연산 프로퍼티
struct Money {
var currencyRate: Double = 1100
var dollar: Double = 0
var won: Double {
get {
return dollar * currencyRate
}
set {
dollar = newValue / currencyRate //set 파라미터 설정을 newValue로 설정
}
}
}
var assets = Money(dollar: 2300, currencyRate: 2)
print(assets.won) //4600
var moneyInMyPocket = Money()
moneyInMyPocket.dollar = 10
print(moneyInMyPocket.won) //11000
//타입 프로퍼티
var account = Account()
account.credit = 1000
struct SomeStructure {
static var storedTypeProperty = "Some value." //타입 프로퍼티
static var computedTypeProperty: Int {
return 1
}
}
SomeStructure.storedTypeProperty = "hello" //인스턴스의 생성없이 접근하여 값을 변경
//프로퍼티 감시자
struct Money {
var currencyRate: Double = 1100 {
willSet(newRate) {
print("환율이 \(currencyRate)에서 \(newRate)으로 변경될 예정입니다")
}
didSet(oldRate) {
print("환율이 \(oldRate)에서 \(currencyRate)으로 변경되었습니다.")
}
}
키 경로
class Person {
var name: String
init(name: String) {
self.name = name
}
}
print(type(of: \Person.name)) //ReferenceWritableKeyPath<Person, String>
인스턴스 메소드
mutating
타입 메소드
class Friend18 {
var name: String
func changeName(newName: String) {
self.name = newName
}
init(_ name: String) {
self.name = name
}
}
var myFriend18 = Friend18("김태형")
myFriend18.changeName(newName: "개발하는 테드")
myFriend18.name //참조 타입이기 때문에 바로 접근하여 값을 바꿀 수 있음
struct BestFriend18 {
var name: String
mutating func changeName(newName: String) { //struct는 mutating을 써주지 않으면 해당 멤버변수의 이름이 바뀌지 않음 !
self.name = newName
}
}
var myBestFriend18 = BestFriend18(name: "태형")
myBestFriend18.changeName(newName: "Ted")
struct SystemVolume {
//타입 프로퍼티를 사용하면 언제나 유일한 값이 된다.
static var volume: Int = 5
//타입 메소드 사용
static func mute() {
self.volume = 0 //SystemVolume.volume = 0과 같은 표현
}
}
[출처] 스위프트 프로그래밍 (야곰), 야곰의 스위프트 기초문법 강좌, 개발하는 정대리 스위프트 강좌