Swift クラス名を文字列で取得

Swift クラスの型名を文字列取得

Swift の 「クラス 変数」 の型名を 文字列で取得する方法

let s: String = "文字列"
let anser: String = String(describing: type(of: s))
print(anser)

変数 anser には 「String」という文字列が入ります。

変数 anser には 「String」という文字列が入ります

Optionalの場合

let i: Int? = 1
let anser: String = String(describing: type(of: i))
print(anser)

上↑の 変数anser には「Optional<Int>」が入りました。

クラスの場合

class TObject {}
let obj1 = TObject()
let anser: String = String(describing: type(of: obj1))
print(anser)

TObjectというクラスを作成しました。

変数 anser には 「TObject」という文字列が入りました。

型名は、 下記のように取り出すこともできます

let anser: String = String(describing: type(of: TObject.self))

もしくは

let anser: String = String(describing: TObject.Type.self)

“TObject.Type”という文字列が入りました。

2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED