Type checking and casting

Swift provides type checking and type casting. We can check the type of a variable with the is keyword. It is most commonly used in if statements, as shown in the following code:

let aConstant = "String"

if aConstant is String {
    print("aConstant is a String")
} else {
    print("aConstant is not a String")
}

As String is a value type and the compiler can infer the type, the Swift compiler will issue a warning because it already knows that aConstant is String. Another example can be the following, where we check whether anyString is String:

let anyString: Any = "string"

if anyString is String {
    print("anyString is a String")
} else {
    print("anyString is not a String")
}

Using the is operator is useful to check the type of a class instance, specifically, the ones that have subclasses. We can use the is operator to determine if an object is an instance of a specific class.

Similarly, we can use the as operator to actually coerce an object to another type than what the compiler has inferred it to be. The as operator comes in two flavors: the plain as operator and as?. The former casts the object into the desired type without asking. If the object cannot be cast to that type, a runtime error is thrown. The as? operator asks an object if it can be cast to a given type. If the object can be cast, then some value is returned; otherwise, nil is returned. The as? operator is most often used as part of an if statement.

Obviously, it's best to use as? whenever possible. We should use as only if we know it will not result in a runtime error.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset