2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift 2.1 で 構造体の名前とか変数名を取得する

Last updated at Posted at 2015-11-27

#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)
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?