以下實例基於Swift4,且在class, struct, enum中都可用:
class Foo { // 實例屬性中指定明確的類名來獲取名稱 var typeName: String { return String(describing: Foo.self) } // 實例屬性中動態獲取類名來獲取名稱 var otherTypeName: String { let thisType = type(of: self) return String(describing: thisType) } // 類屬性中直接獲取名稱 static var typeName: String { return String(describing: self) } } Foo().typeName // = "Foo" Foo().otherTypeName // = "Foo" Foo.typeName // = "Foo"