The role of type conversions

A cast can determine the type of an instance or treat the instance as an instance of its parent or subclass in its class hierarchy.

Type conversions in Swift are implemented as the IS and AS operators. These two operators use a simple, expressive way to check the type of a value or to convert a value to another type.

You can also use type conversions to check whether a type complies with a protocol.

Type checking

Use the type checking operator is to check whether an instance belongs to a particular subclass. The type checking operator returns true if the instance is of the subclass type, false otherwise.

var movieCount = 0
var songCount = 0
 
for item in library {
    if item is Movie {
        movieCount + = 1
    } else if item is Song {
        songCount + = 1}}print("Media\ songs \ contains \(songs) \ songs ")* / / PrintsMedia library contains 2 movies and 3Your songs"*
Copy the code

Downcast

The conversion operator as? Or as! Casts an instance downtype to its subclass type

Because downcasting can fail, the type conversion operator has two different forms. Conditional form, as? , returns an option for the value you want to cast down. Mandatory form, as! , combines downward casting and forced expansion as one step.

How to distinguish between using AS? Or as!

When in doubt, use the conditional form of the type conversion operator as? . If the downward conversion fails, the optional value is nil.

When you are sure that a downward conversion will succeed, use the coercion type conversion operator as! . The cast operator will trigger a runtime error when you cast down to an incorrect type.

for item in library {
    if let movie = item as? Movie {
        print(" the Movie, '\' Movie. The name, dir. \ "(Movie. Director))}else if let song = item as? Song {
        print(“Song: ‘\(song.name)’, by \(song.artist)”)
    }
}
 
* / / Movie: 'Casablanca', dir.Michael Curtiz*
* / / Song: 'Blue Suede Shoes', byElvis Presley*
* / / Movie: 'Citizen Kane', dir.Orson Welles*
* / / Song: 'The One And Only', byChesney Hawkes*
* / / Song: 'Never Gonna Give You Up', byRick Astley*
Copy the code

For example

if let movie = item as? Movie
Copy the code

This can be read as: Try to access item as type Movie. If successful, set a new temporary constant movie to store the returned optional movie type.

The conversion does not actually change the instance or modify its value.

Type conversion of Any and AnyObject

Swift provides two special type aliases for indeterminous types:

  • AnyObjectCan be saidAny classType.
  • AnyCan be saidanyTypes, includingFunction types.
var things = [Any]()
 
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159) things. Append (" hello ") things. Append ((3.0.5.0))
things.append(Movie(the name:"Ghostbusters", the director,"Ivan Reitman")) things. Append ({(name:String) - >String inHello, \}) (name)"Copy the code

You can use the IS and AS operators in switch cases to find specific types of constants or variables that are of type Any or AnyObject.

for thing in things {
    switch thing {
    case let someInt as Int:
        print(" an integer value of \(someInt) ")case let someDouble as Double where someDouble > 0:
        print(" a positive double value of \(someDouble) ")case is Double:
        print("some other double value that IDon 't want to print ")default:
        print(" somethingelse")}}Copy the code

The optional type is converted to Any to avoid warnings

If you use an explicitly declared Any option, Swift will issue a warning meaning you should have passed an Any argument, but you passed an optional argument, and you will receive a warning.

If you really need to use optional in Any, you can eliminate the warning by explicitly converting the optional type to Any with the AS operator.

let optionalNumber: Int? = 3
things.append(optionalNumber)        * / / Warning*
things.append(optionalNumber as Any) * / / No warning*
Copy the code

Swift learning group

Welcome to join my Swift learning wechat group for mutual supervision. My wechat account is Reese90