티스토리 뷰

iOS/Swift

Swift에서의 Class와 Struct

iOS 개발자, 였던 것 2023. 4. 27. 21:49

 

Structures and classes are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions.

 

Struct와 Class를 통해 요소를 유연하게 구성할 수 있다. 클래스 안에 method와 property들을 일반적인 상수, 변수, 메소드 정의하듯 정의하여 사용 할 수 있다고 한다.

 

struct와 class를 비교하면 다음과 같은 공통점이 있는데,

  • 값을 저장하는 property를 정의 할 수 있음
  • 기능 제공을 위한 method를 정의 할 수 있음
  • 서브 스크립트 구문을 이용해 값에 접근을 제공하는 서브 스크립트를 정의할 수 있음
  • 초기화 상태를 설정하기 위한 초기화 정의가 가능
  • 기본적인 구현을 넘어 기능적 확장을 위한 확장
  • 특정 종류의 표준 기능을 제공하는 프로토콜 준수

외에도 Class에는 추가적인 기능이 더 있다.

  • 상속을 사용해 한 클래스가 다른 클래스의 특성을 상속할 수 있음
  • 타입 캐스팅을 사용하면 런타임 내 클래스 인스턴스의 타입을 확인 및 해석 가능
  • 초기화 해제 구문을 사용하면 클래스의 인스턴스가 할당된 리소스를 해제
  • 참조 카운팅은 하나 이상의 클래스 인스턴스 참조를 허락함

 

The additional capabilities that classes support come at the cost of increased complexity. As a general guideline, prefer structures because they’re easier to reason about, and use classes when they’re appropriate or necessary. In practice, this means most of the custom types you define will be structures and enumerations.

 

Swift를 사용하는 일반적인 상황에서는 class 보다는 struct와 enum을 사용할 것을 권장한다.

이는 class 자체가 제공하는 추가 기능들로 인해서, 추론하기 어렵게 만들고 메모리 관리 부분에서도 오류가 날 확률이 높기 때문이다. 반대로 이야기하면 Struct는 제한이 많고 덕분에 사용자가 개발을 하는 과정에서 실수를 일으킬 확률이 낮아서 Struct를 추천한다고 볼 수 있다.

 

Whenever you define a new structure or class, you define a new Swift type. Give types UpperCamelCase names (such as SomeStructure and SomeClass here) to match the capitalization of standard Swift types (such as String, Int, and Bool). Give properties and methods lowerCamelCase names (such as frameRate and incrementCount) to differentiate them from type names.

 

Swift에서 사용하는 기본적인 컨벤션에 대해서도 설명해주는데, 클래스명의 경우는 대문자로 시작하는Upper Camel Case를 기타 메소드나 프로퍼티들의 경우는 일반적인 Camel Case를 사용하도록 권장한다.

 

Class와 Struct의 대표적인 차이는 주소 값으로 참조하느냐 값으로 참조하느냐의 차이가 가장 대표적, Class는 주소 값으로 참조를 하는 만큼 ARC를 통해 메모리가 관리되지만 Struct는 값 자체를 가지기 때문에 서로 간의 간섭이 없다. 아마 이런 부분 때문에 권장하지 않을까 싶다.

 

참고문헌

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/classesandstructures

https://icksw.tistory.com/256

'iOS > Swift' 카테고리의 다른 글

Swift, Equatable?  (0) 2023.04.21
Swift, Set 톺아보기  (0) 2023.04.18
ViewController와 LifeCycle - 2, LifeCycle  (0) 2023.04.18
ViewController와 LifeCycle - 1, UIViewController  (0) 2023.04.16
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함