Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

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.

like image 734
ielyamani Avatar asked Jun 07 '14 13:06

ielyamani


People also ask

How do you check if an object is of a certain class Swift?

“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.

How do you define a class variable in Swift?

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.

What is @testable in Swift?

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.


1 Answers

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 } 
like image 153
Jesse Rusak Avatar answered Oct 14 '22 14:10

Jesse Rusak