목차
**class**
클래스에서의 속성property 선언은 let이나 var 선언과 똑같다. 단, 클래스의 맥락context 안에서 선언한다. 예를 들어, 메소드 혹은 함수 선언와 같은 방식으로 쓴다.
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A Shape with \\(numberOfSides) sides."
}
}
experiment
let colorOfBottom = "red"
func simpleDescriptionColor() -> String {
return "A Shape with \\(colorOfBottom) bottom."
}
var shape = Shape()
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
**var shape = Shape()
** 클래스의 새로운 인스턴스를 만든다. **()**
shape.numberOfsides
를 수정
새로운 변수 var shapeDescription을 만들어서, shpae의 property shape.simpleDescription()
를 할당
init
**init
** 초기화하기
인스턴스가 만들어질 때 클래스를 초기화해야 한다.
class NamedShape {
var numberOfSides: Int = 0
var name: String // name property, 초기화 안됨
init(name: String) { // name argument, 초기화
self.name = name
}
func simpleDescription() -> String {
return "A shape with \\(numberOfSides) sides."
}
}
**self
: 초기화하기 위한 인자 name argument와 클래스 속성의 name property를 구분하기 위해 self가 어떻게 사용되는지 주목하자. name property는 클래스의 새로운 인스턴스가 만들어졌을 때 함수가 호출되는 것처럼 지나간다. 모든 속성property은 할당된 값(numberOfSides) 또는 이니셜라이저(name)가 필요하다.**