본문 바로가기
#모바일 [Mobile]/iOS

[iOS] Swift 구조체와 클래스 차이점 (Struct and Class Difference)

by cy_mos 2020. 2. 15.
반응형
카테고리 게시글 작성 날짜 게시글 최근 수정 날짜 작성자
iOS 2020-02-15 15:08 2021.12.03. 22:58 Dev.Yang

 

🛠 구조체 (Struct)

구조체는 하나 이상의 변수를 묶어서 새로운 자료형을 정의하는 도구입니다. Swift에서의 구조체는 대문자 카멜 케이스를 사용하여 이름을 명명하며 프로퍼티와 메서드는 소문자 카멜 케이스를 사용하여 이름을 명명합니다. 또한 Swift에서의 구조체는 개발자가 직접 이니셜 라이저를 생성하지 않아도 자동적으로 생성이 된 기본 이니셜 라이저를 통하여 구조체의 프로퍼티 이름으로 자동 지정됩니다.

 

Swift에서 구조체를 사용하기 위해서 선언할 때 let으로 선언하는 경우에는 인스턴스 내부의 프로퍼티 값을 변경할 수 없습니다. 하지만 var로 선언하면 내부의 프로퍼티가 var선언 이 된 프로퍼티에 한해서 값을 변경할 수 있습니다. 또한 Apple 공식 문서에 따라서 아래와 같은 경우에는 Struct 자료 형태를 사용하는 것을 권장하고 있습니다.

 

  • Swift의 기본 자료형 타입 (Int, Float, Double, String, Array, Dictionary, Set 등)은 모두 구조체 형태로 구현이 되어있으며, 이는 Swift 기본 자료형 타입은 모두 값 타입이라는 뜻입니다.
  • 값 타입 (Value Type) 형태입니다.

 

구조체 (Struct)를 사용하는 경우는 아래와 같습니다.

  • 연관된 간단한 값의 집합을 캡슐화하는 것만이 목적인 경우
  • 캡슐화한 값을 참조하는 것보다 복사하는 것이 적합한 경우
  • 구조체에 저장 된 프로퍼티가 값 타입이며 참조하는 것보다 복사하는 것이 적합한 경우
  • 다른 타입으로부터 상속받거나 자신을 상속할 필요가 없는 경우

 

아래의 소스코드는 구조체 (Struct) 예제 소스코드입니다.

struct SomeStruct {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aStruct = SomeStruct(name: "Bob")
var bStruct = aStruct // aStruct and bStruct are two structs with the same value!
bStruct.name = "Sue"

println(aStruct.name) // "Bob"
println(bStruct.name) // "Sue"

🛠 클래스 (Class)

객체 지향 프로그래밍에서, 데이터와 그 조작 절차인 메소드를 정리한 객체의 추형을 정의한 것입니다. Swift에서 클래스를 정의할 때에는 class라는 키워드를 사용합니다. 또한 구조체와 동일하게 대문자 카멜 케이스를 사용하여 이름을 명명하며, 프로퍼티와 메서드는 소문자 카멜케이스를 사용하여 이름을 명명합니다.

 

  • Swift 공식 문서에서는 다른 프로그래밍 언어와는 달리 클래스의 인스턴스를 객체가 아닌 인스턴스 용어를 사용할 것을 권장합니다.
  • 참조 타입 (Reference Type) 형태입니다.

🛠 클래스와 구조체 공통점 및 차이점 (Swift Struct and Class Difference) 

class Car {
    var name: String

    init(name:String){
        self.name = name
    }
}

var carA = Car(name: "BMW")
var carB = carA
//now I will change carB
carB.name = "Nissan"
print(carA.name) //This will print Nissan


struct CarStruct {
    var name: String

    init(name: String){
        self.name = name
    }
}

var carC = CarStruct(name: "BMW")
var carD = carC
//now I will change carB
carD.name = "Nissan"
print(carC.name) //This will print BMW

 

✏️ 공통점

  • 값을 저장하기 위해서 프로퍼티를 정의할 수 있습니다.
  • 기능 실행을 위해서 메서드를 정의할 수 있습니다.
  • 서브 스크립트 문법을 통하여 구조체 또는 클래스가 갖는 값에 접근하도록 서브 스크립트를 정의할 수 있습니다.
  • 초기화될 때의 상태를 지정하기 위해서 이니셜 라이저를 정의할 수 있습니다.
  • 초기 구현과 더불어 새로운 기능 추가를 위하여 익스텐션 (Extension)을 통하여 확장할 수 있습니다.
  • 특정 기능을 실행하기 위해서 특정 프로토콜을 준수할 수 있습니다.

 

🇺🇸 원문 내용은 아래의 접은글에서 확인 할 수 있습니다.

더보기
  • Define properties to store values
  • Define methods to provide functionality
  • Define subscripts to provide access to their values using subscript syntax
  • Define initializers to set up their initial state
  • Be extended to expand their functionality beyond a default implementation
  • Conform to protocols to provide standard functionality of a certain kind

 

✏️  차이점

  • 구조체는 클래스와 달리 상속을 할 수 없습니다.
  • 타입 캐스팅은 클래스의 인스턴스에서만 사용이 가능합니다.
  • Deinitializer는 클래스의 인스턴스에서만 사용할 수 있습니다.
  • 참조 횟수 계산 (Reference Counting)은 클래스의 인스턴스에서만 적용됩니다.

 

🇺🇸 원문 내용은 아래의 접은글에서 확인 할 수 있습니다.

더보기
  • Inheritance enables one class to inherit the characteristics of another.
  • Type casting enables you to check and interpret the type of a class instance at runtime.
  • Deinitializers enable an instance of a class to free up any resources it has assigned.
  • Reference counting allows more than one reference to a class instance.

🚀 REFERENCE

더보기
 

structure vs class in swift language

From Apple book "One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by refere...

stackoverflow.com

 

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

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 u

docs.swift.org

 

What are the main differences between classes and structs in swift 3?

The only thing I found is that a struct cannot inherit but a class does, and that a struct is passed by value while a class is passed by reference, but I couldn't understand what is that exactly. Can

stackoverflow.com

 

스위프트 프로그래밍

문법을 넘어 프로그래밍 패러다임도 익히는 스위프트 5스위프트 5의 핵심 키워드는 ‘안정화’다. ABI 안정화 덕분에 버전과 환경에 크게 영향받지 않고 더 유연하게 스위프트를 사용할 수 있게 되었다. 최신 패러다임과 다양한 언어의 기능을 흡수하여 언어 전반에 걸쳐 안정화되었다. 기존 스위프트 업데이트의 주된 목적이 새로운 기능 추가였다면, 이번 스위프트 5는 비약적으로 발전한 기능을 세세하게 보정하고 다듬었다. 그렇다고 굵직한 변화가 없는 것은 아니다. 스

book.naver.com

반응형

댓글