「Swift」type(of:)メソッドでクラスを比較する方法

2022年1月17日

書式
type(of: インスタンス) == クラス名.self

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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)
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)
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

Swift

Posted by arkgame