Created
June 24, 2018 15:59
-
-
Save myssun0325/5cdc5be9a5ac03a635f15ee120b8ce7a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// MetaType_Example | |
// | |
// Created by moon on 2018. 6. 22.. | |
// Copyright © 2018년 moon. All rights reserved. | |
// | |
import Foundation | |
// 1. 기존 방식 -> 객체를 인자로 넣어서 ObjectIdentifier를 획득하는 것이 목적 | |
class 돼지 { | |
var name: String { | |
return "돼지" | |
} | |
} | |
class 족발: 돼지 { | |
override var name: String { | |
return "족발" | |
} | |
} | |
class 삼겹살: 돼지 { | |
override var name: String { | |
return "삼겹살" | |
} | |
} | |
class 베이컨: 돼지 { | |
override var name: String { | |
return "베이컨" | |
} | |
} | |
var 돼지타입저장소: [Int:ObjectIdentifier] = | |
[0: ObjectIdentifier(족발.self), 1: ObjectIdentifier(삼겹살.self),2: ObjectIdentifier(베이컨.self)] | |
func make(_ 입력돼지인스턴스: 돼지) -> ObjectIdentifier? { | |
for 돼지타입의ObjectIdentifier in 돼지타입저장소.values { | |
if ObjectIdentifier(type(of: 입력돼지인스턴스)) == 돼지타입의ObjectIdentifier { | |
return 돼지타입의ObjectIdentifier | |
} | |
} | |
return nil | |
} | |
let 베이컨인스턴스 = 베이컨() | |
let 돼지타입의ObjectIdentifier = make(베이컨인스턴스) | |
// 둘의 결과가 같은것을 확인할 수 있다. | |
print(돼지타입의ObjectIdentifier) // Optional(ObjectIdentifier(0x0000000100635be0)) | |
print(돼지타입저장소[2]) // Optional(ObjectIdentifier(0x0000000100635be0)) | |
// 이를 통해 생성된 ObjectIdentifier로 객체를 생성한다. | |
// 2. 메타타입을 활용하여 객체 생성하기 -> 타입만 알려주면 해당 객체 | |
class 돼지 { | |
var name: String { | |
return "돼지" | |
} | |
required init() { | |
} | |
} | |
class 족발: 돼지 { | |
override var name: String { | |
return "족발" | |
} | |
required init() { | |
// 이 클래스의 custom init | |
} | |
} | |
class 삼겹살: 돼지 { | |
override var name: String { | |
return "삼겹살" | |
} | |
required init() { | |
// 이 클래스의 custom init | |
} | |
} | |
class 베이컨: 돼지 { | |
override var name: String { | |
return "베이컨" | |
} | |
required init() { | |
// 이 클래스의 custom init | |
} | |
} | |
var 돼지타입저장소 = [족발.self, 베이컨.self, 삼겹살.self] | |
func make(_ input: 돼지.Type) -> 돼지 { | |
return input.init() | |
} | |
print(make(돼지타입저장소[1])) // 베이컨 | |
print(make(삼겹살.self)) // 삼겹살 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment