How to Test for the Class of a Variable in Swift

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

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 }

Variable declaration inside of class in Swift

Variable declaration as Class level or the Function level is same as in other programming languages, so it would be great if you understand their basic principle.

Class level variable means that this variable can be accessed throughout the class, that means it can be used in any function of the same class. It also means that if you make the class as public, and that variable as public, then once the class is initialized it could be accessed within your program in other classes. Usually they could create memory issues if you don't manage them properly as they stay in the memory when the class itself is within the memory.

Function level variable can only be accessed within that specific function and not outside that function whether it's the same class or a different class, they have no reference outside their function. Usually they don't create memory issues in your whole program as these variables leave the memory when that function is completely executed.

How can I tell what the class of an instance variable is in Swift

Use type.self to return a type that can be passed into a method that accepts a type-level argument. For example, UILabel.self can be passed to the isKindOfClass method call. The string representation of the class can be found via dynamicType.description():

var label = UILabel()
println(label.dynamicType.description())
println(label.isKindOfClass(UILabel.self))

Swift-3

var label = UILabel()
println(type(of: label).description())

Output
UILabel
true

Here's a bit more background -- there are two expressions to be aware of: the postfix self expression and the dynamic type expression. From the docs:

Postfix Self
A postfix self expression consists of an expression or the name of a
type, immediately followed by .self. It has the following forms:

expression.self
type.self

The first form evaluates to the value of the expression. For example,
x.self evaluates to x.

The second form evaluates to the value of the type. Use this form to
access a type as a value. For example, because SomeClass.self
evaluates to the SomeClass type itself, you can pass it to a function
or method that accepts a type-level argument



Dyamic Type Expression

A dynamicType expression consists of an expression, immediately
followed by .dynamicType. It has the following form:

expression.dynamicType

The expression can’t be the name of a type. The entire dynamicType
expression evaluates to the value of the runtime type of the
expression.

Testing a class which preserves its state in private variables

After researching and discussing with some experts, I come up with the solution that if we want to test a class which preserve it's state then the functionality which is preserving the state should go under a separate class. Which will serve the same purpose as setting the variables as private. So, ZoneUpdateDetector should have a dependency for example: ZoneUpdateStatePreserver and it should keep the state which was previously inside ZoneUpdateDetector

Checking if an object is a given type in Swift

If you want to check against a specific type you can do the following:

if let stringArray = obj as? [String] {
// obj is a string array. Do something with stringArray
}
else {
// obj is not a string array
}

You can use "as!" and that will throw a runtime error if obj is not of type [String]

let stringArray = obj as! [String]

You can also check one element at a time:

let items : [Any] = ["Hello", "World"]
for obj in items {
if let str = obj as? String {
// obj is a String. Do something with str
}
else {
// obj is not a String
}
}

how to check the type of a variable in swift

You can do this with the is operator.
Example code:

var test: AnyObject

test = 12.2

if test is Double {
println("Double type")
} else if test is Int {
println("Int type")
} else if test is Float {
println("Float type")
} else {
println("Unkown type")
}

According to Apple docs:

Checking Type

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.



Related Topics



Leave a reply



Submit