「Swift」type(of:)メソッドでクラスを比較する方法
書式
type(of: インスタンス) == クラス名.self
使用例
class Sample {
let age = 32
let no = 3002
}
// Sampleクラスを継承
class Student: Sample {
let addr = "tokyo"
let grade = "A"
}
let ps = Student()
print ("of: インスタンスでクラスを比較")
print(type(of: ps))
print("クラス名.selfで自身クラスを比較")
print(type(of: ps) == Student.self)
print("継承元クラス名.selfで比較")
print(type(of:ps) == Sample.self)
結果
of: インスタンスでクラスを比較
Student
クラス名.selfで自身クラスを比較
true
継承元クラス名.selfで比較
false