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

前端 未结 4 2232
猫巷女王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 20:53

    Swift has the is operator to test the type of a value:

    var onlyUILabels = myArray.filter { $0 is UILabel }
    

    As a side note, this will still produce an Array<UIView>, not Array<UILabel>. As of the Swift 2 beta series, you can use flatMap for this:

    var onlyUILabels = myArray.flatMap { $0 as? UILabel }
    

    Previously (Swift 1), you could cast, which works but feels a bit ugly.

    var onlyUILabels = myArray.filter { $0 is UILabel } as! Array<UILabel>
    

    Or else you need some way to build a list of just the labels. I don't see anything standard, though. Maybe something like:

    extension Array {
        func mapOptional<U>(f: (T -> U?)) -> Array<U> {
            var result = Array<U>()
            for original in self {
                let transformed: U? = f(original)
                if let transformed = transformed {
                    result.append(transformed)
                }
            }
            return result
        }
    }
    var onlyUILabels = myArray.mapOptional { $0 as? UILabel }
    
    0 讨论(0)
  • 2020-12-08 20:54

    You may compare classes using the following in swift:

     return object.dynamicType == otherObject.dynamicType
    

    dynamicType will return an instance of Class which you may compare

    0 讨论(0)
  • 2020-12-08 21:02

    In Swift you should do the is keyword if you are wondering about the according class. In the filter-closure you can use $0 to specify the first parameter.

    Sample

    var (a,b,c,d) = ("String", 42, 10.0, "secondString")
    let myArray: Array<Any> = [a,b,c,d]
    var onlyStrings = myArray.filter({ return $0 is String })
    onlyStrings // ["String", "secondString"]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题