TIL/Swift 내용 정리

Swift Deep Dive: Class Struct Enum

여의도사노비 2023. 2. 7. 15:58
728x90

1️⃣ Class

In Swift, a class is a blueprint for creating objects, providing initial values for state (member variables or properties) and implementations of behavior (member functions or methods). Classes are used to model real-world objects and encapsulate data and behavior. Instances of a class can be created, and the state and behavior of each instance can be modified dynamically at runtime. Classes can also inherit properties and methods from a parent class, making it easier to reuse and extend existing code.

 

Swift에서 클래스는 상태(멤버 변수 또는 속성) 및 동작 구현(멤버 함수 또는 메서드)에 대한 초기 값을 제공하는 객체 생성을 위한 청사진입니다. 클래스는 실제 개체를 모델링하고 데이터와 동작을 캡슐화하는 데 사용됩니다. 클래스의 인스턴스를 생성할 수 있으며 각 인스턴스의 상태와 동작은 런타임에 동적으로 수정할 수 있습니다. 클래스는 부모 클래스에서 속성과 메서드를 상속할 수도 있으므로 기존 코드를 더 쉽게 재사용하고 확장할 수 있습니다.

 

 

2️⃣ Struct

In Swift, a Struct is a value type data structure. It is used to define a custom data type that encapsulates a set of related values. Structs are similar to classes, but they have some key differences. Some of these differences include:

  • Structs are value types, meaning that they are copied when they are assigned to a variable or passed as an argument to a function.
  • Structs cannot inherit from other structs or classes.
  • Structs do not have deinitializers.

 

Structs are typically used for simple data structures that don't require inheritance, such as points in 2D or 3D space, color values, or rectangles. They are generally preferred over classes for value types because they are more efficient and easier to use.

 

Swift에서 Struct는 값 유형 데이터 구조입니다. 관련 값 세트를 캡슐화하는 사용자 정의 데이터 유형을 정의하는 데 사용됩니다. 구조체는 클래스와 유사하지만 몇 가지 중요한 차이점이 있습니다. 이러한 차이점 중 일부는 다음과 같습니다.

  • 구조체는 변수에 할당되거나 함수에 인수로 전달될 때 복사되는 값 유형입니다. (클래스는 참조 유형)
  • 구조체는 다른 구조체나 클래스에서 상속할 수 없습니다.
  • 구조체에는 초기화 해제자(deinitializer)가 없습니다.

 

구조체는 일반적으로 2D 또는 3D 공간의 점, 색상 값 또는 사각형과 같이 상속이 필요하지 않은 단순한 데이터 구조에 사용됩니다. 더 효율적이고 사용하기 쉽기 때문에 일반적으로 값 유형의 클래스보다 선호됩니다.

 

 

3️⃣ Enum

In Swift, an Enum (short for enumeration) is a data type that defines a set of related values. An enumeration can be thought of as a group of named values that represent a common type.

Some of the key features of enums in Swift include:

  • Enums define a new type and can be used like any other type in Swift (such as String or Int).
  • Enums can have associated values, which allow each case to store its own unique values.
  • Enums can have methods and computed properties just like classes and structs.
  • Enums can conform to protocols and can be used in switch statements to handle different cases.

 

Enums are often used to define a set of mutually exclusive options or states, such as the values of a card suit in a deck of playing cards or the states of a network request. Enums can also be used to model complex data structures, such as the parse tree of a computer program.

 

Swift에서 Enum(열거형의 약자)은 관련 값 집합을 정의하는 데이터 유형입니다. 열거형은 공통 유형을 나타내는 명명된 값의 그룹으로 생각할 수 있습니다.

Swift에서 열거형의 주요 기능 중 일부는 다음과 같습니다.

  • 열거형은 새로운 유형을 정의하고 Swift의 다른 유형(예: String 또는 Int)처럼 사용할 수 있습니다.
  • 열거형은 연관된 값을 가질 수 있으므로 각 케이스가 고유한 값을 저장할 수 있습니다. (Struct와 같은 값 타입)
  • 열거형은 클래스 및 구조체와 마찬가지로 메서드 및 계산된 속성을 가질 수 있습니다.
  • 열거형은 프로토콜을 준수할 수 있으며 다른 경우를 처리하기 위해 switch 문에서 사용할 수 있습니다.

 

열거형은 종종 네트워크 요청 상태와 같이 상호 배타적인 옵션 또는 상태 집합을 정의하는 데 사용됩니다. 열거형은 컴퓨터 프로그램의 구문 분석 트리와 같은 복잡한 데이터 구조를 모델링하는 데에도 사용할 수 있습니다.

 

 

Brief Comparison

일반적으로 코드에서 전달될 때 복사되는 유형을 원하면 구조체를 사용해야 하고 참조되는 유형을 원하면 클래스를 사용해야 합니다. 열거형은 관련된 값의 한정된 집합이 있고 함께 그룹화하려는 경우에 유용합니다.

Class Structure Enumeration
  • 참조 유형(객체는 힙에 저장되고 포인터에 의해 참조됨)
  • 상속 및 다형성 지원
  • deinitializer를 사용하여 리소스를 해제할 수 있다.
  • 참조 시맨틱은 의도하지 않은 부작용을 초래할 수 있다.
  • 값 유형(객체가 참조가 아닌 단일 값으로 저장됨)
  • 상속 또는 다형성 없음
  • deinitializer를 사용할 수 없다.
  • 다중 스레딩을 위한 더 예측 가능하고 안전한 동작 
  • 관련 값 목록을 정의하는 데 사용된다.
  • 상속 또는 다형성 없음
  • 메서드, 이니셜라이저 및 계산된 속성을 연결할 수 있다.
  • 관련 값 집합을 나타내는 간결하고 읽기 쉬운 방법을 제공한다.

 

+) About reference semantic

"참조 시맨틱에서(= Class) 변수는 개체의 실제 값을 저장하지 않고 대신 개체가 저장된 메모리 위치에 대한 참조를 저장합니다. 즉, 여러 변수가 동일한 개체를 참조하는 경우 해당 개체에 대한 모든 변경 사항은 해당 개체를 참조하는 모든 변수에 영향을 미칩니다. 이것은 프로그래머가 참조된 개체의 공유 특성을 인식하지 못하는 경우 때때로 의도하지 않은 부작용으로 이어질 수 있습니다. "