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: CGRectMake(0, 0, 200, 20)) var u3 = UITableView(frame: CGRectMake(0, 20, 200, 80)) var myArray = [u1, u2, u3] var onlyUILabels = myArray.filter({"what to put here?"})
Without bridging to objective-c.
“Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
Declaring VariablesYou begin a variable declaration with the var keyword followed by the name of the variable. Next, you add a colon, followed by the variable type. Afterward, you can assign a value to the variable using the (=) assignment operator.
This makes swift entities declared in the complied module eligible for higher level of access. 2. When we add @testable attribute to an import statement for module complied with testing enabled, we activate elevated access for that module in that scope.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With