[Swift 기본문법] property

dora·2024년 3월 15일

Swift 기본 문법

목록 보기
6/12

Property

struct, class, enum에 type과 관련된 값을 정의할 때 쓴다.

  • 저장 프로퍼티(stored property)
  • 연산 프로퍼티(computed property)
  • 인스턴스 프로퍼티(instance property)
  • 타입 프로퍼티(type property)
struct Student{
	//인스턴스 저장 프로퍼티
    var name: String
    var `class` : String = "Swift"
    var koreanAge: Int = 0
    
    //인스턴스 연산 프로퍼티
    var westernAge: Int{
    	get{
        	return koreanAge - 1
        }
        set(inputValue){
        	koreanAge = inputValue + 1
        }
    }
    
    //타입 저장 프로퍼티
    static var typeDescription: String = "학생"
    
    //읽기 전용 타입 연산 프로퍼티
    //읽기 전용에서는 get을 생략할 수 있다
    static var selfIntroduction: String{
    	return "학생타입입니다"
    }
}

print(Student.selfIntroduction)

var dora: Student = Student()
dora.koreanAge = 10

dora.name = "dora"
print(dora.name)

print(dora.selfIntroduction)
print("제 한국나이는 \(dora.koreanAge)살이고, 미국 나이는 \(dora.westernAge)살입니다.")
struct Money{
	var currencyRate: Double = 1100
    var dollar: Double = 0
    var won: Double{
    	get{
        	return dollar * currencyRate
        }set{
        	dollar = newValue / currencyRate
        }
    }
}

var moneyInMyPocket = Money()
moneyInMyPocket.won = 111000
print(moneyInMyPocket.won)

moneyInMyPocket.dollar = 10
print(moneyInMyPocket.won)

저장 프로퍼티와 연산 프로퍼티의 기능

함수, 메서드, 클로저, 타입 등의 외부에 외치한 전역 변수에도 모두 사용가능하다

var a: Int = 100
var b: Int = 200
var sum: Int {
	return a + b
}

print(sum)

Property Observer

프로퍼티 감시자를 사용하면 값이 변경될 때 원하는 동작을 수행할 수 있다

struct Money{

	//프로퍼티 감시자 1
	var currencyRate: Double = 1100{
    	willSet(newRate){
        	print("환율이 \(currencyRate)에서 \(newRate)으로 변경될 예정입니다")
        }
        didSet(oldRate){
        	print("환율이 \(oldRate)에서 \(currencyRate)으로 변경되었습니다.")
        }
    }
    
    //프로퍼티 감시자 2
    var dollar: Double = 0 {
    	willSet{
        	print("\(dollar)에서 \(newValue)달러로 변경될 예정입니다")
        }
        didSet{
        	print("\(oldValue)"달러에서 \(dollar)달러로 변경되었습니다)
        }
    }
    
    //연산 프로퍼티
    var won: Double{
    	get{
        	return dollar * currencyRate
        }
        set{
        	dollar = newValue / currencyRate
        }
    }
}

var moneyInMyPocket: Money = Money()

moneyInMyPocket.currencyRate = 1150
moneyInMyPocket.dollar = 10

print(moneyInMyPocket.won)
var a: Int = 100{

	willSet{
    	print("\(a)에서 \(newValue)로 변경될 예정입니다")
    }
    didSet{
    	print("\(oldValue)에서 \(a)로 변경되었습니다")
    }
}

a = 200

0개의 댓글