判断“变量”或“对象”的类型

  • 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.self {
            //...
        } else if mirrorType == Dictionary.self {
            //...
        } else if mirrorType == UIView.self {
            //...
        } else {
            //...
        }
    }

你可能感兴趣的:(判断“变量”或“对象”的类型)