Swift

[LanguageGuide] Structures and Classes

moving 2022. 12. 29. 22:54
728x90

구조체와 클래스 비교

공통점

  • 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

클래스만 가지고 있는 특성

  • 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.

참고

구조체와 클래스는 String, Int, 및 Bool 과 같은 타입이며, 따라서 UpperCamelCase 따르고 프로퍼티와 메서드는 타입과 구분짓기 위해 lowerCamelCase 를 따른다.

struct Resolution {
    var width = 0
    var height = 0
}

class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

구조체와 클래스 인스턴스

위 코드의 클래스와 구조체는 생긴 모양만 보여줄뿐 이를 사용하기 위해서는 인스턴스를 만들어야한다.

let someResolution = Resolution()
let someVideoMode = VideoMode()

구조체와 클래스는 모두 새 인스턴스에 초기화 구문을 사용합니다.

위의 코드는 모든 속성이 기본값으로 초기화된 클래스 또는 구조체의 인스턴스를 생성하는 코드입니다.

프로퍼티에 접근

.을 사용해서 인스턴스의 프로퍼티에 접근할 수 있습니다.

print("The width of someResolution is \(someResolution.width)")
// Prints "The width of someResolution is 0"

또한 변수 프로퍼티에 값을 할당하기 위해서도 사용할 수 있습니다.

someVideoMode.resolution.width = 1280
print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
// Prints "The width of someVideoMode is now 1280"

구조체의 멤버와이즈 이니셜라이저

구조체는 프로퍼티의 이름으로 매개변수를 갖는 이니셜라이저인 멤버와이즈 이니셜라이저를 기본으로 제공합니다.

let vga = Resolution(width: 640, height: 480)

구조체와 열거형은 값타입

값타입은 변수 또는 상수에 할당되거나 함수에 전달될 때 값이 복사되는 유형입니다.

스위프트의 기본적인 타입들은 모두 값타입이며, 구조체로 구현되어 있습니다.

표준 라이브러리에 의해 정의된 컬렉션은 최적화를 사용하여 복사 성능 비용을 줄입니다. 즉, 즉시 복사본을 만드는 대신 원본 인스턴스와 복사본 간에 요소가 저장된 메모리를 공유합니다. 컬렉션의 복사본 중 하나가 수정되면 수정 직전에 요소가 복사됩니다.

Untitled

클래스는 참조타입

참조타입은 변수나 상수에 할당되거나 함수에 전달될 때 복사되지 않습니다. 복사가 아니라 동일한 기존 인스턴스에 대한 참조가 사용됩니다.

Untitled

참조타입은 추론이 힘들다. 왜냐하면 같은 인스턴스를 참조하고 있다면 모두 생각해야하기 때문이다.

let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0

클래스의 인스턴스 생성시 상수(let)로 선언해도 클래스의 프로퍼티 값을 바꿀 수 있습니다. 왜냐하면 인스턴스 자체는 클래스를 저장하지 않습니다. 둘 다 배후에서 VideoMode 인스턴스를 참조합니다. 변경된 것은 해당 VideoMode에 대한 상수 참조 값이 아니라 기본 VideoMode의 프로퍼티입니다.

ID 연산자

클래스는 참조 타입이기 때문에 여러 상수와 변수가 동일한 인스턴스를 참조할 수 있습니다.

따라서 두 개의 상수 또는 변수가 클래스의 동일한 인스턴스를 참조하는지 여부를 확인할 수 있습니다.

  • Identical to (===)
  • Not identical to (!==)
if tenEighty === alsoTenEighty {
    print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}

===는 클래스 타입의 두 상수 또는 변수가 정확히 같은 인스턴스틑 참조함을 의미합니다.

==는 타입의 디자이너가 정의한 것과 같이 두 인스턴스가 값이 같거나 같은 것으로 간주됨을 의미합니다.