判断“变量”或“对象”的类型
2017-06-14 本文已影响6人
冰霜海胆
- 1、在
swift
中,判断一个“对象”的类型:
let view1 = UIView()
view1.isKind(of: UIView.self)
view1.isMember(of: UIView.self)
- 2、或者是通过
is
关键字:
let number1: Int = 10
let numberIsInt = (number1 is Int) ? true : false
- 3、 或者通过
Mirror
:
let string = "Hello World!"
let array = [1, 2, 3, 4, 5, 6]
let dict = ["1": 1, "2": 2, "3": 3]
let view = UIView()
let data = Data()
func judgmentClass(_ obj: Any) {
let mirrorType = Mirror(reflecting: obj).subjectType
if mirrorType == String.self {
//...
} else if mirrorType == Array<Int>.self {
//...
} else if mirrorType == Dictionary<String, Int>.self {
//...
} else if mirrorType == UIView.self {
//...
} else {
//...
}
}