How to test for the class of a variable in Swift?

前端 未结 4 2233
猫巷女王i
猫巷女王i 2020-12-08 20:15

I want to check if the elements of an Array are a subclass of UILabel in Swift:

import UIKit

var u1 = UILabel()
u1.text=\"hello\"
var u2 = UIView(frame: CGR         


        
4条回答
  •  自闭症患者
    2020-12-08 21:02

    Without getting to the object.class( ) nirvana, in Swift, we can still use the Objective-C Runtime to get some useful information about the object´s class as follows (and not exactly bridging to Objective-C):

    let objectClass: AnyClass = object_getClass(object) as AnyClass
    let objectClassName =  NSStringFromClass(objectClass)
    println("Class = \(objectClassName)")
    

    Note that we get the "MyProject." or (sometimes) the "Swift." prefix, depending if you refer to your own classes or Swift classes:

    UILabel // UILabel    
    Swift._NSSwiftArrayImpl //Swift Array
    MyProject.Customer_Customer_   //for a CoreData class named Customer
    

提交回复
热议问题