💥 메타 타입
- 타입의 타입을 뜻한다.
- 우리가 알고 있는 타입은 메타타입의 인스턴스이다*
- 위의 내용을 표로 정리해보면 아래와 같다.
메타타입 | String.type |
---|---|
메타타입의 인스턴스(타입) | String.self |
타입의 인스턴스 | “Miro” |
- 예를 통해서 표의 내용을 이해해보자. 아래는 Class를 정의하고 해당 클래스의 인스턴스를 생성해주는 코드이다.
class Human {
var: name = "Miro"
}
let miro: Human = Human()
miro 상수와 같이 Human 타입이라고 선언했을 경우, Human 타입의 instance를 넣어준다.
그렇다면 아래와 같은 코드일 경우, 메타타입의 instance(Human.self)를 넣어주어야됨을 알 수 있다.
let humanType: Human.Type = Human.self //Human이라고하면 에러
🫧 JSON Parsing 속 메타타입
- 우리는 아래와 같은 방식으로 JSON 파일을 parsing한다.
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}
let json = """
{
"name": "Durian",
"points": 600,
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)
print(product.name) // Prints "Durian"
- 위의 코드에서 사용되는 decode 메소드의 경우, 첫번째 파라미터로
T.Type
의 인스턴스를 넣어주어야된다. - 따라서
GroceryProduct.type
의 인스턴스GroceryProduct.self
가 첫번째 파라미터로 들어가야된다.
func decode<T>(
_ type: T.Type,
from data: Data
) throws -> T where T : Decodable
'Swift' 카테고리의 다른 글
[Swift] 배열 안전하게 조회하기 (0) | 2023.02.04 |
---|---|
[Swift] Optional (0) | 2023.02.04 |
[Swift] Generic (0) | 2023.02.03 |
[Swift] map 삼형제(map, compactMap, flatMap) (0) | 2023.02.03 |
[Swift] Protocol (0) | 2023.02.03 |