본문 바로가기

Programming/Swift

타입: Structures (구조체) and Classes (클래스) vs. Enumerations (열거형)

중요 개념: 타입/ 인스턴스/ 프로퍼티/ 메서드

 

A type = a blueprint

An instance = a house (you built from the blueprint)

 

블루프린트는 각 집의 features 특징과 behaviors 행동을 보여줌.

 

Features -> properties

Behaviors -> methods

 

e.g. 지하철 매표 자판기

Features (= properties)

  • 색깔
  • 크기

Behaviors (= methods)

  • 돈 출력
  • 표 출력

블루프린트는 각 집의 features (프로퍼티)와 behavior (메서드)를 보여줌.

In a type, features are called properties

And behaviors are called methods.

 

Properties

Var color = green

Var bedrooms = 2

>> a property = a variable defined inside a type

 

Methods

runWater()

turnLightsOn()

>> a method = a function defined inside a type

 

  • 각 집의 Garage door를 연다고 치자

herHouse/ myHouse/ hisHouse

 

어느 집에서, 뭘 할지를 얘기해줘야 함

myHouse.openGarageDoor()

 

myHouse = the instance (a specific house)

openGarageDoor() = the method (from the myHouse instance)

 

*** Structures (구조체) and Classes vs. Enumerations (열거형)

구조체와 클래스는 데이터를 용도에 맞게 묶어 표현하고자 유용.

 

Comparing Structures and Classes

Structures and classes in Swift have many things in common. Both can:

  • 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

 

클래스는 구조체와 달리 상속받을 수 있다.

Classes have additional capabilities that structures don’t have:

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

The syntax for creating instances is very similar for both structures and classes:

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

Structures and classes both use initializer syntax for new instances. 

Accessing Properties

 

You can access the properties of an instance using dot syntax. In dot syntax, you write the property name immediately after the instance name, separated by a period (.), without any spaces:

  • print("The width of someResolution is \(someResolution.width)")

Structures and Enumerations Are Value Types

값 타입이란건 또 하나의 복사본 (또 하나의 인스턴스)를 만들어내는 것

겉으로 보이는 결과물은 같아 보일지는 몰라도!

 

value type is a type whose value is copied when it’s assigned to a variable or constant, or when it’s passed to a function.

 

You’ve actually been using value types extensively throughout the previous chapters. In fact, all of the basic types in Swift—integers, floating-point numbers, Booleans, strings, arrays and dictionaries—are value types, and are implemented as structures behind the scenes.

 

All structures and enumerations are value types in Swift. This means that any structure and enumeration instances you create—and any value types they have as properties—are always copied when they’re passed around in your code.

 

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

This example declares a constant called hd and sets it to a Resolution instance initialized with the width and height of full HD video (1920 pixels wide by 1080 pixels high).

 

It then declares a variable called cinema and sets it to the current value of hd. Because Resolution is a structure, a copy of the existing instance is made, and this new copy is assigned to cinema. Even though hd and cinema now have the same width and height, they’re two completely different instances behind the scenes.

 

Classes Are Reference Types

Unlike value types, reference types are not copied when they’re assigned to a variable or constant, or when they’re passed to a function. Rather than a copy, a reference to the same existing instance is used.

 

클래스는 참조 타입이라서 변수를 만들때 새로운 카피본이 생겨나는 것이 아니라

이미 존재하는 인스턴스에 대한 레퍼런스가 이용됨

 

값타입은 새로운 인스턴스의 공간을 만들어주는 것이라면

참조타입은 그 값이 어디있는지? 위치만 알려주는 것

새로운 공간을 따로 만들어내지 않고

 

구조체를 언제 사용할지? <출처: 애플 가이드라인>

*** Enumerations

 

An enumeration defines <a common type> for a group of related values 

and enables you to work with those values in a type-safe way within your code.

 

Alternatively, enumeration cases can specify associated values of any type to be stored along with each different case value.

 

자신의 프로퍼티 값을 수정할 떄 클래스의 인스턴스 메서드는 크게 신경 쓸 필요가 없지만,

구조체나 열거형 등은 타입이므로 메서드 앞에 mutating  키워드를 붙여서 해당 메서드가 인스턴스 내부의 값을 변경한다는 것을 명시해야 .

'Programming > Swift' 카테고리의 다른 글

야곰 스위프트 기초 퀴즈 - 데이터 타입  (0) 2021.03.05
continue vs. return vs. break  (0) 2021.03.04
if let vs. guard let  (0) 2021.03.04
GCD Concepts  (0) 2021.02.10
[ios] Self-Sizing Table View Cells  (0) 2021.01.22