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

前端 未结 4 2234
猫巷女王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, not Array. 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
    

    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(f: (T -> U?)) -> Array {
            var result = Array()
            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 }
    

提交回复
热议问题