1. struct가 heap에 저장된다고?

우리는 value type이니까 ⇒ stack 영역에, class는 reference type 이니까 ⇒ heap 영역에 저장한다고 생각했다… 근데…

”일반적으로 value type은 stack영역, reference type은 heap영역에 저장 하지만, **struct타입이 heap에 할당되는 경우가 상당히 많이 존재”

다시 공부를 시작해보자..!!!**

1-1. struct가 프로토콜을 confirm 하는 경우

i) 예시코드

→ 우리는 다형성을 위해서 Struct를 Protocol과 같이 사용할 수 잇는데영 아래와 같이 작성했다고 해봅시당!

그리고 Drawable 타입을 인자로 받아서 *draw()*메서드를 호출하는 drawACopy(_:)  함수가 있습니다.

protocol Drawable {
  func draw()
}

struct Point: Drawable {
    let x, y: Double
    
    func draw() {
      print("\\(x), \\(y)")
    }
}

struct Line: Drawable {
    let x1, y1: Double
    let x2, y2: Double
    
    func draw() {
      print("\\(x1), \\(y1) - \\(x2), \\(y2)")
    }
}
func drawACopy(_ local: Drawable) {
   local.draw()
}

⇒ 이 코드에 성능은 Struct로 했으니까 좋겠찌? 가 아닙니다.. 왜일까요?

drawACopy(:) 라는 함수는 Drawable을 인자로 받는 함수라서 Drawable protocol 을 구현한 모든 타입들이 인자로 전달받을 수 있죱

⇒ 졸라 큰 class, 졸라 큰 strcut, 작은 class, 작은 struct 등…. 다 받을 수 있음

⇒ 컴파일 타임에 local 이라는 변수의 크기를 하나로 단정 지을 수 없습니다. 🤯

class VeryLargeViewcontroller: UIViewController, Drawable {
    let view1: UIView
    // .....
    let view100: UIView
    
    func draw() {}
}

struct Large: Drawable {
    let fromZeroToMillion: [Int] = [0, 1, 2, 3, 4, .... 10_000_000]
  
    func draw() {}
}

struct Small: Drawable {
    func draw() {}
}

어떻게 하면 코끼리를 냉장고에 넣을 수 있을까요?

어떻게 하면 코끼리를 냉장고에 넣을 수 있을까요?

ii) Existential Container

existential container는 작은 value타입들을 담는 버퍼인데 큰 값들의 경우에는 힙에 할당하고 existential container에서는 그 메모리에 대한 포인터를 저장

Untitled