|
class |
struct |
enum |
데이터 참고 방식 |
reference type |
value type |
value type |
저장 위치 |
Heap 영역 |
Stack 영역 |
Stack 영역 |
상속 가능 유 / 무 |
가능 |
불가능 |
불가능 |
Extension 가능 유 / 무 |
가능 |
불가능 |
불가능 |
속도 |
느림 |
빠름 |
빠름 |
ARC 유 / 무 |
가짐 |
안가짐 |
안가짐 |
클래스보다 struct를 쓰기 좋을 때
1. 연관된 간단한 값의 집합을 캡슐화하는 것만이 목적일 때
2. 캡슐화한 값을 참조하는 것보다 복사하는 것이 합당할 때
3. 구조체에 저장된 프로퍼티가 값 타입이며 참조하는 것보다 복사하는 것이 합당할 때
4. 다른 타입으로부터 상속받거나 자신을 상속할 필요가 없을 때
enum보다 struct를 쓰기 좋을 때
해당 내용에 대해서 마땅한 비교가 없기에 struct의 특징을 파악하며 비교를 해보았다.
struct의 특징은 "서로 다른 자료형 타입을 하나로 묶을 수 있어 새로운 타입으로 사용 가능하다"는 것이다.
즉, 다른 자료형 타입을 하나로 묶을 수 있어 새로운 타입으로 사용할 때 enum이 아닌 struct를 사용하는 것이 더 효과적이다.
+ 추가
스택 오버플로우를 보다가 enum에 관한 글을 볼 수가 있었다.
해당 질문은 enum에서 값이 변경되는 것을 파악할 수가 있냐는 질문이었고 대답은 아래와 같다.
No. An enum is a value type. When the value changes, the old value is completely destroyed and replaced with a new one.
If you want mutable state, you should use a class or mutable struct, and didSet with a property. |
아니요. 열거형은 값 유형입니다. 값이 변경되면 이전 값은 완전히 파기되고 새 값으로 대체됩니다.
didSet변경 가능한 상태를 원하면 속성 과 함께 클래스 또는 변경 가능한 구조체를 사용해야 합니다. |
즉, 만일 swift에서 didSet과 같은 상태를 원할 경우에도 enum이 아닌 struct를 쓰는 것이 효과적일 것이다.
* 추가
struct와 enum은 ARC를 안가지는데 어떻게 메모리를 자동적으로 초기화할수 있는가?
반면에 구조체와 열거형은 인스턴스를 인라인으로 저장합니다.
- 전역 변수로 선언되면 프로그램 텍스트에 저장됩니다.
- 지역 변수로 선언되면 스택(또는 레지스터에 할당되지만 신경쓰지 않음)에 할당됩니다.
- 다른 개체의 속성으로 할당된 경우 해당 개체 내에 직접 인라인으로 저장됩니다.
함수가 반환되거나 객체가 할당 해제되는 경우와 같이 포함하는 컨텍스트가 할당 해제되는 경우에만 삭제됩니다 |
On the other hand, structs and enums just have their instances stored inline:
- If they're declared as a global variable, they're stored in the program text.
- If they're declared as a local variable, they're allocated on the stack (or in registers, but never mind that).
- If they're allocated as a property of another object, they're just stored directly inline within that object.
They're only ever deleted by virtue of their containing context being deallocated, such as when a function returns, or when an object is deallocated. |
출처 : https://seons-dev.tistory.com/entry/Swift-%EA%B8%B0%EC%B4%88%EB%AC%B8%EB%B2%951-CLASS-STRUCT-ENUM(서근 블로그)
https://stackoverflow.com/questions/60116339/arc-doesnt-apply-to-struct-and-enum-how-are-they-deallocated-in-swift(스택 오버플로우)
https://stackoverflow.com/questions/37681455/swift-enum-perform-code-on-value-change/37682471#37682471(스택 오버플로우)