Structures and Classes - The Swift Programming Language (Swift 5.6)
Structures and Classes
Structure와 class는 프로그램 코드의 구성요소가 되는 광범위하고 유연한 구조이다.
- 메서드와 프로퍼티 정의가 가능하다.
- 다른 언어와 다르게, 커스텀 structure와 class에 분리된 인터페이스나 구현파일을 요구하지 않는다.
- 클래스의 인스턴스는 전통적으로 object로 알려져 있다. 그러나 스위프트 structure와 class의 instance 들은 다른언어와는 다르게 기능적이다 그러므로 object가 아닌 instance라 칭한다
Comparing Structures and Classes
- 공통점:
- 저장 값으로 프로퍼티 정의
- 기능성 제공을 위해 메서드 정의
- 그들의 value 에 접근하기 위해 subscript sytax사용을 제공하는 subscripts 정의
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2 // [,] 는 subsctipt brackets 라고 부른다
- 초기 상태 설정을 위해 이니셜라이저 정의
- 기본 구현을 넘어선 기능확장을 위해 extended
- 특정 종류의 표준기능을 제공하기 위해 protocol 준수
Class만 가진 추가 기능(struct엔 없음)
- 상속은 한 class 가 다른 class의 특성들을 상속받을 수 있게 해준다
- 타입캐스팅은 런타임시 클래스 인스턴스의 타입을 확인하고 해석할 수 있게 해준다
- class의 인스턴스의 Deinitializer는 할당된 어느 자원이든 해제 시켜준다
- ReferenceCounting 은 클래스 인스턴스에 대한 하나 이상 참조를 허락한다
- 일반적 가이드라인으로, 추론하기 더 쉬운 Struct사용을 권장한다
- class는 그것이 적합하고 필요할 때 사용하라