longlivedrgn
Miro 찾기
longlivedrgn
전체 방문자
오늘
어제
  • 분류 전체보기 (74)
    • Swift (36)
    • iOS (31)
    • Algorithm (0)
    • Architecture, Design Patter.. (1)
    • Computer Science (6)
      • 컴퓨터 네트워크 (6)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
longlivedrgn

Miro 찾기

[Swift] 값 타입, 참조 타입, let, var
Swift

[Swift] 값 타입, 참조 타입, let, var

2023. 2. 24. 23:18

let VS var

struct

  • 구조체의 경우, 그 안의 프로퍼티 값을 변경하려면 무조건 var로 인스턴스를 생성해야된다.
  • 단, 프로퍼티는 Struct 안에서 var로 선언되어있어야된다.
struct Struct {
    var string = "happy"
}

let structInstance = Struct()
structInstance.string = "sad" // error

class

  • 클래스의 경우, 그 안의 프로퍼티 값을 변경할 때, var나 let이나 상관없이 인스턴스를 생성해주면된다.
  • 단, 프로퍼티는 클래스 안에서 var로 선언되어있어야된다.
class Class {
    var string = "happy"
}

let classInstance = Class()
classInstance.string = "sad" // OK

즉, 구조체의 경우 그 안에 있는 프로퍼티 값이 변경될 경우, 구조체를 무조건 var로 선언을 해야된다!

즉, 클래스일 경우 그 안에 있는 프로퍼티 값이 변경될 경우, let이나 var나 상관없다!


구조체 안에 클래스가 있는 경우

  • 구조체 안에 있는 클래스 타입의 프로퍼티의 프로퍼티를 변경할 경우!
    • 복사본이 변경되면 원본도 변경이된다!(클래스의 프로퍼티)
class Class {
    var string = "happy"
}

struct Struct {
    var string = "happy"
    // let이던 var던 상관없다!
    let classType = Class()
}

let structInstance = Struct()
// 무조건 var여야된다!
var copiedStructInstance = structInstance

copiedStructInstance.string = "sad"
copiedStructInstance.classType.string = "sad"

structInstance.string // "happy" -> 복사값이 변경되어도 원본값은 변경되지 않는다.
structInstance.classType.string // "sad" -> 원본값도 변경이된다.

클래스 안에 구조체가 있는 경우

  • 클래스 안에 있는 구조체 타입의 프로퍼티의 프로퍼티 값을 변경할 경우
    • 복사본이 변경되면 원본값도 변경된다!
struct Struct {
    var string = "happy"
}

class Class {
    var string = "happy"
    // let으로 설정하면 error 생긴다.
    var structType = Struct()
}

let classInstance = Class()
let copiedClassInstance = classInstance

copiedClassInstance.string = "sad"
copiedClassInstance.structType.string = "sad"

classInstance.string // "sad"
classInstance.structType.string // "sad"
저작자표시 (새창열림)

'Swift' 카테고리의 다른 글

[Swift] Enumeration(열거형)  (0) 2023.03.06
[Swift] mutating  (0) 2023.02.24
[Swift] 함수 return에대한 고민  (0) 2023.02.20
[Swift] Error Handling  (0) 2023.02.11
[Swift] 프로퍼티 옵저버  (0) 2023.02.11
    'Swift' 카테고리의 다른 글
    • [Swift] Enumeration(열거형)
    • [Swift] mutating
    • [Swift] 함수 return에대한 고민
    • [Swift] Error Handling
    longlivedrgn
    longlivedrgn

    티스토리툴바