#Swift 2.1で自信のクラス名とかを取ってみるメモ。
Swiftのバージョンによって違うようなので 2.1 でやってみた場合
これができるということは、データをjson/sql/xml化をextensionで実装できたりしそうであるが、実行速度が遅いぽいので沢山呼ばれるところでは使用しないほうがいいぽい。。。
けど、覚えておくと実装の幅が広がると思うのでメモ
MyPlayground.playground
struct ProgrammingLangage {
var name: String
var version: Int
var revision: Int
var vender: String
}
extension ProgrammingLangage {
var customDescription: String {
get {
let mirror = Mirror(reflecting: self)
var customDescription: String
customDescription = String(mirror.subjectType)
customDescription += "("
var isFirst = true
for case let(label?, value) in mirror.children {
if !isFirst {
customDescription += ", "
}
customDescription += label
customDescription += ": "
let valueMirror = Mirror(reflecting: value)
customDescription += String(valueMirror.subjectType)
customDescription += "="
customDescription += String(value)
isFirst = false
}
customDescription += ")"
return customDescription
}
}
}
let swift = ProgrammingLangage(name: "Swift", version: 2, revision: 1, vender: "Apple")
print(swift)
// ProgrammingLangage(name: "Swift", version: 2, revision: 1, vender: "Apple"
print(swift.customDescription)
// ProgrammingLangage(name: String=Swift, version: Int=2, revision: Int=1, vender: String=Apple)