Structure은 Stack에 저장
Class는 Heap에 저장
Stack은 빠르고 효율적임. 빨리 처리해야하는 것들을 stack에 생성
Heap은 느리고 메모리를 자동저장 하지 않기 때문에 더 신경써야함
주로 변수 및 reference를 stack에 저장하고 class를 heap에 저장함.
Struct 써야하는 경우
- 두 object를 "같다, 다르다"로 비교해야하는 경우
- copy된 각 객체들이 독립적인 상태를 가져야 하는 경우
- 코드에서 오브젝트의 데이터를 여러 스레드에 걸쳐 사용할 경우
(struct는 value type이라서 copy 되기 때문에 위험도가 떨어짐)
Class 써야하는 경우
- 두 object의 instance(객체) 자체가 같음을 확인해야할때
- 하나의 객체가 필요하고, 여러 대상에 의해 접근되고 변경이 필요한 경우 ex) UIapplication
일단 struct로 쓰자.
: 나중에 class로 바꿔야되면 바꾸면 됨, swift는 struct를 더 선호함
(참조: https://developer.apple.com/swift/blog/?id=10, stackoverflow)
: 중복된 내용을 풀 수 있는 방법
학생은 -> 사람이다 처럼 명제 성립이 가능한 경우에만 사용 가능
사용하는 법
class Student: Person{
var grades: [Grades] = []
// 여기에 있던 나머지 부분들은 person을 상속함으로써 생략 가능
}
Super Class(parent class, 더 포괄적인 클래스) ex. Person
Sub Class(child class) ex. Student
- 자식은 한 개의 super class만 상속받음
- 부모는 여러 자식 가질 수 있음
- 상속의 깊이는 상관없음
✨ Sub class에서 Super class method 변경하고 싶을 때 override 사용하면 됨
✨ sub class의 객체를 super class의 객체에 할당이 가능하다.
override func train() {
trainedtime += 2
} // football player class 안에서 studentahtlete꺼 override함
athelte1: StudentAthlete
athelte2: FootballPlayer
athlete1 = athlete 2(as StudentAthlete) //uppercast, 더 높은 단계의 class에 할당
athlete1.train() // +2
athlete1.footballTeam // 오류남
//이런 경우에는 down casting해서 사용 가능
if let son = athlete1 as?FootballPlayer{
print("\(son.footballTeam)")}
// Team: FC Swift
class에서 property 생성하는 경우 초기값을 줘야함
2-phase initialization 클래스 생성 시 2가지 단계
(property, method 사용 전에 initialized 먼저 꼭 돼야함)
phase 1 (이 단계가 다 끝나기 전에는 어떠한 property, method도 사용 불가)
모든 stored property는 모두 initialized 돼야한다 (자식부터)
순서가 아래에서 위로
person
|
student
|
studentAthlete - super.init(...), self.sports=...
phase 2 (phase1과 반대로 작용)
부모꺼 먼저 setting, 순서가 위에서 아래로
person
|
student
|
studentAthlete
-> convenience initializer 사용하면 됨 (부생성자라고 부르기도 함)
convenience init(name: String) {
self.init (firstName: name, lastName: "", sports: []}
우리가 기존에 사용하는 initializer를 designated initializer이라고 부름