본문 바로가기
Swift

[Swift] Extension에 Stored Property를 못 넣는 이유

by Sky Titan 2022. 9. 27.
728x90
 

Swift Interview Questions and Answers

In this tutorial, you’ll work through a series of Swift-specific interview questions and answers.

www.raywenderlich.com

 

Why does Swift not allow stored properties in extensions?

I've been trying to find the best way to implement a stored property in an extension, and came across this question: Swift extension stored properties alternative. However, I have not found a reaso...

 

stackoverflow.com

 

What's the reasoning for "Extensions may not contain stored properties"?

Posted in r/swift by u/yellowliz4rd • 6 points and 5 comments

www.reddit.com

Extension에 Stored Property를 못 넣는 이유

 Compiler가 어떤 객체의 instance를 생성하기 위해선 필요한 메모리의 총량을 알 수 있어야 한다.
 함수, computed property를 추가하는 것은 추가적인 메모리를 필요로 하는 행위가 아니기에 문제가 될 것이 없지만 stored property는 추가적인 메모리를 필요로 하기에 extension에서 만약 stored property가 선언이 되면 아래와 같은 경우에 문제가 된다.

 

 만약 class 혹은 struct가 module안에서 선언이 되어 있는 경우, 그리고 extension은 다른 module에서 선언이 되어있는 경우에 만약 extension에서 추가적인 메모리가 필요한 stored property가 선언이 된다면 해당 module은 extension을 인지하고 난 이후에 다시 한 번 컴파일이 되어야 하는 상황이 발생한다.

 이것은 module의 encapsulation을 깨뜨리고 기본적인 목적을 저해하는 행위가 된다.

 (반대로 생각해보면 이론적으로는 하나의 module 안에서는 extension에 stored property를 쓰는 것이 가능할 수도 있다.)

 

 따라서 Extension은 기본적으로 추가적인 메모리를 요구하는 상황이 발생하면 안된다.

728x90

'Swift' 카테고리의 다른 글

[Swift] Int vs Int32, Int64  (0) 2023.01.07
[Swift] Extension에서의 Override  (0) 2022.10.01
[Swift] Generic where clause 사용 시 '==' vs ':'  (0) 2022.09.25
[Swift] JSON Decoding, Encoding  (0) 2022.09.05
[Swift] Swift Object Lifetime  (0) 2022.08.26

댓글