Struct, class 는 범용적 목적의 유연한 구조로 프로그램의 building block 이 됨.

다른 언어와 다르게 Swift 는 custom struct, class 를 위한 별개의 interface, implementation 파일이 필요 없고 하나의 파일에 정의하면 딤

Comparing Structures and Classes

Class 의 추가 능력으로 인해 증가한 복잡도로 cost 가 발생할 수 있음. 일반적으로 struct 를 지향하고, 필요한 경우에만 class 사용. 대부분의 custom type 은 struct / enum 이 될 것.

Class 와 actor 는 특징, 동작에서의 공통점이 많음

Definition Syntax

struct, class 모두 비슷한 definition syntax 를 가짐. struct / class 를 정의할 때 새로운 type 을 정의하는 것이기 때문에 UpperCamelCase 이름을 쓰고, property 와 method 는 lowerCamelCase 이름을 씀

struct SomeStructure {
    // structure definition goes here
}

class SomeClass {
    // class definition goes here
}

Structure and Class Instances

Initializer syntax 를 통해 새 instance 를 생성

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()

Accessing Properties

dot syntax 를 통해 인스턴스의 property 에 접근 / 새 값을 할당할 수 있음

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

Memberwise Initializers for Structure Types

모든 struct 는 자동으로 memberwise initializer 가 생성됨.

Memberwise initializer : 새 instance 의 member property 들을 초기화할 때 사용할 수 있음.

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

Structures and Enumerations Are Value Types

Value type : 상수/변수에 할당 되거나 함수에 전달될 때 copy 되는 타입

Swift 의 기본 type (Int, float-point, Bool, string, array, dictionary) 는 struct 로 구현된 value type

모든 struct, enum 은 value type. 생성한 모든 struct / enum instance 는 코드에서 전달될 때 항상 복사됨

Collections (array, dictionary, string, …) 은 copy 의 성능 cost 를 줄이기 위한 최적화를 사용함. 복사본을 즉시 만들지 않고, 원래 instance 와 복사된 것들이 공유된 메모리에 접근하게 함. 만약 복사된 것 중에 하나가 수정됐다면 수정 직전에 collection 요소들이 복사됨.

let hd = Resolution(width: 1920, height: 1080)
// Resolution 이 struct 이기 때문에 이미 존재하는 instance hd 의 복사본이 생성돼서 cinema 에 할당됨
var cinema = hd

cinema.width = 2048

print("cinema is now \(cinema.width) pixels wide") 
// Prints "cinema is now 2048 pixels wide".

print("hd is still \(hd.width) pixels wide") 
// Prints "hd is still 1920 pixels wide".

Classes Are Reference Types

Reference type : 상수/변수에 할당되거나 함수에 전달될 때 copy 되지 않음

복사 대신에 같은 instance 에 대한 참조가 사용됨

// let 으로 선언해도 내부 property 변할 수 있음. instance 자체가 바뀌는 것은 아니기 때문
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0

let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0

Identity Operators

Class 가 reference type 이기 때문에 여러 상수 / 변수를 하나의 같은 class instance 를 참조하도록 하는게 가능함

두 상수/변수가 같은 class 인스턴스를 참조하는지 확인 가능

if tenEighty === alsoTenEighty {
    print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}
// Prints "tenEighty and alsoTenEighty refer to the same VideoMode instance."

‘Equal to’ 는 custom struct / class 를 정의할 때 개발자가 어떻게 충족시킬지를 조건을 생각해야 함

Pointers

Reference type 을 참조하는 Swift 상수/변수는 C 의 pointer 와 비슷하긴 하지만 메모리의 주소를 직접 가리키는 pointer 가 아니고, 참조를 만들고 있다는 뜻의 asterisk * 를 붙일 필요 없음.

Swift 는 pointer 를 사용해야 하는 경우르 위해 pointer 와 buffer type 을 제공함