티스토리 뷰

🍏/Swift

[Swift] Self Type

eungding 2021. 11. 22. 00:51
반응형

Self vs self - what's the difference? 에 대해서는 대충 알고 있었지만, 
예전에 iOS Test-Driven Development by Tutorials (raywenderlich) 를 보다가 

샘플코드 중, 이런 식으로 되어있는 것을 보고 좀 헷갈려서 Self Type 문서를 봐야지~~ 했는데 이제야 봅니다,,, 

 

 

 

https://docs.swift.org/swift-book/ReferenceManual/Types.html#grammar_self-type

 

Types — The Swift Programming Language (Swift 5.5)

Types In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it’s defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a

docs.swift.org

 

Self type은 specific type은 아니고, current type을 의미합니다. 

해당 type의 이름을 알지 않고도, current type을 편하게 참조할 수 있고

해당 type의 이름을 반복하며 코드를 작성해주기 싫을 때 유용하게 사용할 수 있습니다. 

 

protocol, structure, class, enum 안에서 사용할 수 있습니다.

예를들어 class 안에서 Self는 아래와 같은 항목에서 사용될 수 있습니다. 

- As the return type of a method
- As the return type of a read-only subscript
- As the type of a read-only computed property
- In the body of a method

 

 

Self type은  type(of:) function과 같은 type을 참조합니다.  
Self.someStaticMember 와 type(of: self).someStaticMember 는 같습니다. 

 

 

그리고 문서에서 나오는 예제! 

 

class Superclass {
    func f() -> Self { return self }
}

class Subclass: Superclass { }


let x = Superclass()
print(type(of: x.f()))
// Prints "Superclass"


let y = Subclass()
print(type(of: y.f()))
// Prints "Subclass"


let z: Superclass = Subclass()
print(type(of: z.f()))
// Prints "Subclass"


마지막 예제는 Self가  compile-time type (SuperClass) 이 아니라 runtime type (Subclass) 를 참조한다는 것을 보여줍니다.

 



+

 

아래 블로그 글 엄청 친절하게 설명해주셔서 추천!

 

https://wodyios.tistory.com/2

 

[Swift] Self와 self의 차이

이 글은 개념 정리 용도로 작성하였기 때문에 잘못된 지식이 있을 수 있습니다! 보실 경우, 댓글로 지적해주시면 감사하겠습니다 🤗🤗🤗 SwiftUI Tutorial을 따라하다가 처음 보는 용어가 나왔습

wodyios.tistory.com

 

 

 

반응형

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

Swift, Dart, Python % Operator 비교  (0) 2021.12.07
[Swift] assert, precondition, fatalError  (1) 2021.12.05
[Swift Algorithms] chunks(ofCount:)  (0) 2021.09.28
[Swift] async / await 사용사례  (0) 2021.07.06
[Swift] async / await 동작원리  (0) 2021.07.06
댓글