본문 바로가기

프로그래밍/iOS

구조체(Struct) 클래스(Class)의 공통점과 차이점

공통점

  • 값을 저장하기 위한 Properties 정의

  • 기능을 제공하기 위한 Methods 정의

  • Subscript 문법을 이용해 특정 값을 접근할 수 있는 Subscript 정의

  • initial 상태를 설정할 수 있는 initializers 정의

  • 기본 구현에서 기능 확장

  • 특정한 종류의 표준 기능을 제공하기 위한 Protocols 순응

차이점

Struct

  • 값 타임

    • 인자로 보내거나 배열에 넣거나 심지어 다른 변수에 할당해도 복사가 된다.

    • IOS에서는 배열, 정수형, 문자열, 딕셔너리 등 구조체로 구성되어 있다.

  • Copy On Write (COW)

    • 무언가를 전달할 때 모든 내용을 하나하나 전부 복사하지 않는다.

    • 누군가 내용을 변경했을 때만 실제로 복사하도록 하는 전달 방식을 취한다.

Class

  • 래퍼런스 타입

    • Heap에 자료형이 담겨있고 그 자료형에 포인터를 쓸 수 있다.

    • 여러 군데에서 사용한다면 실제로 그 자료형을 보내는 게 아닌 그 자료형을 가르키는 포인터를 보낸다.

  • 상속 (Inheritance): 클래스의 여러 속성을 다른 클래스에 물려주는 기능

  • 타입 캐스팅 (Type casting): 런타임에 클래스 인스턴스의 타입을 확인

  • 소멸자 (Deinitializers): 할당된 자원을 해제(free up) 시킴

  • 참조 카운트 (Reference counting): 클래스 인스턴스에 하나 이상의 참조가 가능

출처 1: Swift 공식 문서

 

Structures and Classes — The Swift Programming Language (Swift 5.3)

Structures and Classes 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

docs.swift.org

출처 2: Developing iOS 11 Apps with Swift by Stanford 2번째 강의 MVC

 

Developing iOS 11 Apps with Swift - Free Course by Stanford on iTunes U

Developing iOS 11 Apps with Swift, Stanford, Computer Science, iTunes U, educational content, iTunes U

itunes.apple.com