「Swift」type(of:)でクラスを比較するサンプル

2021年7月20日

書式
type(of:オブジェクト名) ==クラス名.self
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Person {
let target="yuu"
}
// Personクラスを継承
class Student: Person {
let str = "study"
}
let cft = Student()
//クラスの型
print(type(of: cft))
print(type(of: cft) == Student.self)
print(type(of: cft) == Person.self)
class Person { let target="yuu" } // Personクラスを継承 class Student: Person { let str = "study" } let cft = Student() //クラスの型 print(type(of: cft)) print(type(of: cft) == Student.self) print(type(of: cft) == Person.self)
class Person {
  let target="yuu"
}
 
// Personクラスを継承
class Student: Person {
    let str = "study"
}
 
let cft = Student()
//クラスの型
print(type(of: cft))
print(type(of: cft) == Student.self)
print(type(of: cft) == Person.self)

実行結果
Student
true
false

Swift

Posted by arkgame