소소한개발팁
article thumbnail
반응형

 

Comparing Classes and Structures 

- 클래스와 구조체의 공통점

 

  • 값을 저장하기 위한 프로퍼티 정의할 수 있습니다.
  • 기능을 제공하기 위한 메서드 정의할 수 있습니다.
  • subscript 문법을 이용해 특정 값을 접근할 수 있는 subscript 정의할 수 있습니다.
  • 초기 상태를 설정할 수 있는 initializer 정의할 수 있습니다.
  • 기본 구현에서 기능 확장할 수 있습니다.
  • 특정한 종류의 표준 기능을 제공하기 위한 프로토콜 순응합니다.

 

- 클래스만 가능한 점

 

  • 상속 (Inheritance) : 클래스의 여러 속성을 다른 클래스에 물려줄 수 있습니다.
  • 타입 캐스팅 (Type casting) : 런타임에 클래스 인스턴스의 타입을 확인할 수 있습니다.
  • 소멸자 (Deinitializers) : 할당된 자원을 해제(free up) 시킬 수 있습니다.
  • 참조 카운트 (Reference counting) : 클래스 인스턴스에 하나 이상의 참조가 가능합니다.

 

 

Definition Syntax 

- 클래스는 class 키워드를 구조체는 struct 키워드를 이름 앞에 적어서 선언할 수 있습니다.

 

struct SomeStructure {
// structure definition goes here
}
class SomeClass {
// class definition goes here
}

 

- 새로운 클래스나 구조체를 선언할 때마다 Swift 에서 정말 새로운 타입을 선언하는 것입니다. 그래서 이름을 다른 표준 Swift 타입(String, Int, Bool)과 같이 UpperCamelCase 이름(SomeClass, SomeStructure 등)으로 선언합니다. 반대로 프로퍼티나 메서드는 lowerCamelCase(frameRate, incrementCount 등)으로 선언합니다.

 

- struct의 예시입니다.

 

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

 

- class의 예시입니다.

 

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

 

 

 

Structure and Class Instances 

- 구조체와 클래스 이름 뒤에 빈 괄호를 적으면 각각의 인스턴스를 생성할 수 있습니다.

 

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

 

 

Accessing Properties 

- 점(.)을 통해 클래스/구조체 인스턴스의 프로퍼티에 접근할 수 있습니다.

 

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

 

- 하위 레벨 프로퍼티도 점(.)을 이용해 접근할 수 있습니다.

 

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

 

- 점(.)을 이용해 값을 할당할 수 있습니다.

 

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

 

- Swift에서는 하위 레벨의 구조체 프로퍼티도 직접 설정할 수 있습니다. 위 예를 들면 someVideoMode.resolution.width = 1280처럼

 

 

Memberwise Initializers for Structure Types 

- 모든 구조체는 초기화 시 프로퍼티를 선언할 수 있는 초기자를 자동으로 생성하여 제공해줍니다.

  아래와 같은 멤버의 초기화는 구조체 안에 widthheight 프로퍼티만 정의했다면 자동으로 사용 가능합니다.

 

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

 

 

Structures and Enumerations Are Value Types 

- 값 타입이라는 뜻은, 이것이 함수에서 상수나 변수에 전달될 때 그 값이 복사되서 전달되는

   Swift에서 모든 구조체와 열거형 타입은 값 타입입니다.

 

let hd = Resolution(width: 1920, height: 1080)
var cinema = hd

 

 

- Resolution Resolution의 인스턴스 hd를 선언합니다. 그리고 hd를 cinema라는 변수에 할당했습니다. 이런 경우 할당되는 순간 복사되기 때문에 cinemahd는 같지 않고 완전히 다른 인스턴스입니다.

 

cinema.width = 2048

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

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

 

- 열거형에서도 일치합니다.

 

enum CompassPoint {
    case north, south, east, west
}
var currentDirection = CompassPoint.west
let rememberedDirection = currentDirection
currentDirection = .east

if rememberedDirection == .west {
    print("The remembered direction is still .west")
}
// "The remembered direction is still .west"

 

 

Classes Are Reference Types 

- 값 타입과 달리 참조 타입은 변수나 상수에 값을 할당을 하거나 함수에 인자로 전달할 때 그 값이 복사되지 않고 참조됩니다. 아래는 예시입니다.

 

let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0

let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0

print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
// "The frameRate property of tenEighty is now 30.0"

 

- let alsoTenEighty = tenEighty 코드에서 alsoTenEighty 상수가 tenEighty 인스턴스를 복사한 것이 아니라 참조한 것이기 때문에 값이 변경되는 것을 알 수 있습니다.

 

 

 Identity Operator 

- 클래스는 참조 타입이기 때문에 여러 상수와 변수에서 같은 인스턴스를 참조할 수 있습니다. 상수와 변수가 같은 인스턴스를 참조하고 있는지 비교하기 위해 식별 연산자를 사용 가능합니다.

 

  • === : 두 상수나 변수가 같은 인스턴스를 참조하고 있는 경우 참
  • !== : 두 상수나 변수가 다른 인스턴스를 참조하고 있는 경우 참

 

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

 

- 식별 연산자(===)는 비교 연산자(==)와 같지 않습니다. 식별 연산자는 참조를 비교하는 것이고, 비교 연산자는 값을 비교합니다.

 

 

 Pointers 

- Swift는 C, C++, Objective-C에서 포인터와 다르게 다른 상수와 변수처럼 정의해서 사용합니다.

 

 

내용은 https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html를 보면서 작성하였고 원문으로 작성된 내용을 옮기다 보니 이상한 부분이 있을 수 있습니다. 자세한 내용은 위의 링크를 확인해주시기 바랍니다.

 

반응형

'컴퓨터 언어 > Swift' 카테고리의 다른 글

(Swift) 10. Methods (메소드)  (0) 2021.12.11
(Swift) 9. Properties (특성)  (0) 2021.12.11
(Swift) 7. Enumerations (열거형)  (0) 2021.12.09
(Swift) 6. Closures (클로저)  (0) 2021.12.09
(Swift) 5. Functions (함수)  (0) 2021.12.07
profile

소소한개발팁

@개발자 뱅

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!