Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

sanichdaniel의 iOS 개발 블로그

type(of:) 본문

swift

type(of:)

sanich8355 2020. 9. 5. 15:04

값의 dynamic 타입을 리턴해주는 함수

 

static 타입: 컴파일 타임에 타입

dynamic 타입: 런타임에 실제 타입

 

 

아래의 예시에서 count 변수는 static, dynamic 타입이 모두 Int이다.

하지만 value 인자의 static 타입은 Any이고, dynamic 타입은 Int이다. 

func printInfo(_ value: Any) {
    let t = type(of: value)
    print("'\(value)' of type '\(t)'")
}

let count: Int = 5
printInfo(count)
// '5' of type 'Int'

 

protocol MyProtocol {}

class SomeClass: MyProtocol {}

let someClass: MyProtocol = SomeClass()
print(type(of: someClass))
// SomeClass

 

// TODO: 번역, 이해하기 Finding the Dynamic Type in a Generic Context

Normally, you don’t need to be aware of the difference between concrete and existential metatypes, but calling type(of:) can yield unexpected results in a generic context with a type parameter bound to a protocol. In a case like this, where a generic parameter T is bound to a protocol P, the type parameter is not statically known to be a protocol type in the body of the generic function. As a result, type(of:) can only produce the concrete metatype P.Protocol.

The following example defines a printGenericInfo(_:) function that takes a generic parameter and declares the String type’s conformance to a new protocol P. When printGenericInfo(_:) is called with a string that has P as its static type, the call to type(of:) returns P.self instead of String.self (the dynamic type inside the parameter).

 

func printGenericInfo<T>(_ value: T) {
    let t = type(of: value)
    print("'\(value)' of type '\(t)'")
}

protocol P {}
extension String: P {}

let stringAsP: P = "Hello!"
printGenericInfo(stringAsP)
// 'Hello!' of type 'P'

 

This unexpected result occurs because the call to type(of: value) inside printGenericInfo(_:) must return a metatype that is an instance of T.Type, but String.self (the expected dynamic type) is not an instance of P.Type (the concrete metatype of value). To get the dynamic type inside value in this generic context, cast the parameter to Any when calling type(of:).

 

func betterPrintGenericInfo<T>(_ value: T) {
    let t = type(of: value as Any)
    print("'\(value)' of type '\(t)'")
}

betterPrintGenericInfo(stringAsP)
// 'Hello!' of type 'String'

 

출처: developer.apple.com/documentation/swift/2885064-type

'swift' 카테고리의 다른 글

enum vs protocol as UseCase  (0) 2020.09.28
Type Erasure  (0) 2020.09.28
initializer  (0) 2020.09.26
Self Type  (0) 2020.09.05
Metatype  (0) 2020.09.03