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

前端 未结 4 2236
猫巷女王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

    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 = [a,b,c,d]
    var onlyStrings = myArray.filter({ return $0 is String })
    onlyStrings // ["String", "secondString"]
    

提交回复
热议问题