Swift 값 타입과 참조 타입(2020.10.29)

K S Michael·2020년 10월 29일

swift TIL

목록 보기
9/29

class

전통적인 OOP 관점에서의 클래스
단일상속
(인스턴스/타입) 메서드
(인스턴스/타입) 프로퍼티

  • 참조타입
    Apple 프레임워크의 대부분의 큰 뼈대는 모두 클래스로 구성

struct

C언어 등의 구조체보다 다양한 기능
상속불가
(인스턴스/타입)메서드
(인스턴스/타입) 프로퍼티

  • 값타입
    Swift의 대부분의 큰 뼈대는 모두 구조체로 구성

Enum

다른언어의 열거형과는 많이 다른 존재
상속불가
(인스턴스/타입)메서드
(인스턴스/타입) 프로퍼티

  • 값타입

Enumeration
유사한 종류의 여러 값을 유의미한 이름으로 한 곳에 모아 정의
예) 요일, 상태값, 월(Month) 등

열거형 자체가 하나의 데이터 타입
열거형의 case 하나하나 전부 하나의 유의미한 값으로 취급

선언 키워드 - enum

구조체는 언제 사용하나?

  • 연관된 몇몇의 값들을 모아서 하나의 데이터 타입으로 표현하고 싶을때

  • 다른 객체 또는 함수 등으로 전달될때
    참조가 아닌 복사를 원할때

  • 자신을 상속할 필요가 없거나 자신이 다른 타입을 상속받을 필요가 없을때

  • Apple 프레임워크에서 프로그래밍을 할 때에 주로 클래스를 많이 사용

Value vs Reference

  • Value
    데이터를 전달할 때 값을 복사하여 전달
  • Reference
    데이터를 전달할 때 값의 메모리 위치를 전달

자바스크립트의 얕은 복사(shallow copy) 깊은 복사(deep copy) 와 비슷한것 같다.

struct ValueType{
   var property = 1
}
class ReferenceType{
   var property = 1
}

let firstStructInstance = ValueType()
var secondStructInstance = firstStructInstance
secondStructInstance.property = 2

print("first struct instance property : \(firstStructInstance.property)") //1
print("second struct instance property : \(secondStructInstance.property)") //2

// ValueType 은 값을 복사해서 저장하고 저장된 데이터는 원본 데이터에 영향을 주지 않는다.

let firstClassInstance = ReferenceType()
var secondClassInstance = firstClassInstance
secondClassInstance.property = 2

print("first class instance property : \(firstClassInstance.property)") //1
print("second class instance property : \(secondClassInstance.property)") //2

// ReferenceType 은 바라보는 방향(대상)이 같다.
// 같은 곳을 바라보고 있기 때문에 어느쪽에서 값을 변경하면 다른쪽에서도 값이 변경된다.

Quiz 01

	struct SomeStruct{
    	var someProperty: String = "Property" 
    }
    var someStructInstance: SomeStruct = SomeStruct()
    func someFunction(structInstance:SomeStruct){
    	var localVar: SomeStruct = structInstance
        localVar.someProperty = "ABC"
    }
    someFuncton(someStructInstance)
    print(someStructInstance.someProperty)

답: 아래 박스를 드래그해서 영역 선택해 보세요

"Property"

Quiz 02

	class SomeStruct{
    	var someProperty: String = "Property" 
    }
    var someClassInstance: SomeClass = SomeClass()
    func someFunction(classInstance:SomeClass){
    	var localVar: SomeClass = classInstance
        localVar.someProperty = "ABC"
    }
    someFuncton(someClassInstance)
    print(someClassInstance.someProperty)

답: 아래 박스를 드래그해서 영역 선택해 보세요

"ABC"

Data types in Swift

모두 구조체로 되어있다.

public struct Int
public struct Double
public struct String
public struct Dictionary<Key : Hashable , Value>
public struct Array
public struct Set

Swift LOVEs Struct

스위프트는 구조체, 열거형 사용을 선호
Apple 프레임워크는 대부분 클래스 사용
Apple 프레임워크 사용시 구조체/클래스 선택은 우리의 몫이다!!

출처 : 유튜브 "yagom"

profile
차근차근

0개의 댓글