구조체는 값 타입이다.
class는 참조 타입이다. 다중 상속이 안된다.
class 이름 {
구현부
}
class Sample {
var mutableProperty: Int = 100 // 가변 프로퍼티
let immutableProperty: Int = 100 // 불변 프로퍼티
static var typeProperty:Int = 100 // 타입 프로퍼티
func instanceMethod(){
print("instance method")
}
// 타입메서드
// 재정의 불가 타입 메서드 - static
static func typeMethod(){
print("type method - static")
}
// 재정의 가능 타입 메서드 - class
class func classMethod(){
print("type method - class")
}
}
let 과 var 키워드로 선언된 인스턴스는 var로 선언된 프로퍼티를 수정할수 있다.
var mutableReference : Sample = Sample()
mutableReference.mutableProperty = 200
mutableReference.immutableProperty = 200 // class 프로퍼티가 let 으로 선언됨
let immutableReference : Sample = Sample()
immutableReference.mutableProperty = 200
// immutableReference.immutableProperty = 200
// immutableReference = mutableReference
// 타입 프로퍼티 및 메서드
Sample.typeProperty = 300
Sample.typeMethod() // type method
// mutableReference.typeProperty = 400
// mutableReference.typeMethod()
class Student {
var name : String = "unknown"
var `class` : String = "Swift"
class func selfIntroduce(){
print("학생타입입니다.")
}
func selfIntroduce(){
print("저는 \(self.class)반 \(name)입니다.")
}
}
Student.selfIntroduce() // 학생타입입니다.
var yaogom : Student = Student ()
yagom.name = "yagom"
yagom.class = "스위프트"
yagom.selfIntroduce() // 저는 스위프트반 yagom입니다.
let jina: Student = Student()
jina.name = "jina"
jina.selfIntroduce() //저는 Swift반 jina 입니다.
출처 : 유튜브 "yagom"