본문 바로가기
iOS/Swift

Existential Type (any)

by Jiseong 2025. 3. 2.

Existential Type이란 기존 Protocol을 통한 추상 타입을 타입으로서 사용하는 경우를 말한다.

 

여태껏 사용했던 타입으로서의 프로토콜이 Existential Type이다.

 

any 키워드가 등장한 배경은 컴파일 시점에 프로토콜을 채택하고 있는 명확한 타입을 모르므로 Dynamic Dispatch를 사용하여 진행하는데, 이는 컴파일 시점에 프로토콜을 참조하고 있는 객체를 컨테이너에 저장(Boxing values of protocol types)하고 테이블을 참조하여 실행되어야 할 특정 기능을 찾는 데에 비용을 소모하기 때문에 무분별한 사용을 줄이고자 any 키워드를 붙여 개발자에게 명시적으로 보여주기 위함이다.

In addition to heap allocation and reference counting, code using existential types incurs pointer indirection and dynamic method dispatch that cannot be optimized away

In reality, the need for the dynamism they provided is relatively rare compared to the need for generics, but the language makes existential types too easy to reach for, especially by mistake. The cost of using existential types should not be hidden, and programmers should explicitly opt into these semantics.

사용

protocol A { }

struct AStruct: A { }

let a: any A = AStrcut()

 

 

https://github.com/swiftlang/swift-evolution/blob/main/proposals/0335-existential-any.md?source=post_page-----afb50eed02ce---------------------------------------

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

[Swift] Opaque Types  (0) 2025.02.22
[Swift] VisionKit OCR  (2) 2024.10.07
[Swift] UITableView, UICollectionView Last IndexPath  (1) 2023.12.05
[iOS] View Drawing Cycle (Layout까지 작성함)  (0) 2022.08.07
[Xcode] 단축키 좀 써주세요...  (0) 2022.08.06

댓글