iOS development Language Swift entry---type conversion

Source: Internet
Author: User

iOS development language Swift Getting started serial-type conversion

A type conversion can determine the type of an instance, or it can be considered an instance of its parent class or child class.
Type conversions are implemented in Swift using the IS and as operators. These two operators provide a simple way to check the type of a value or convert its type.
You can also use it to check whether a class implements a protocol, as described in the Checking for Protocol conformance section.
Define a class hierarchy as an example
You can use it on hierarchies of classes and subclasses, examine the type of a particular class instance, and convert the type of the class instance to another type in that hierarchy. The following three code snippets define a class hierarchy and an array containing several instances of these classes as examples of type conversions.
The first code fragment defines a new base class Mediaitem. This class provides the underlying functionality for any media item that appears in the digital library. In particular, it declares a String-type Name property, and an init name initializer. (It assumes that all media items have a name.) )

class MediaItem {    name: String    init(name: String) {        self.namename    }}

The next code snippet defines the two subclasses of Mediaitem. The first sub-class, movie, adds a director attribute, and the corresponding initializer, based on the parent class (or base Class). The second class adds a artist (artist) attribute on top of the parent class, and the corresponding initializer:

class Movie: MediaItem {    varString    StringString) {        self.director = director        super.init(name: name)    }}class Song: MediaItem {    varString    StringString) {        self.artist = artist        super.init(name: name)    }}

The last code snippet creates an array constant library that contains two movie instances and three song instances. The type of the library is inferred from what it contains in its array when it is initialized. Swift's type detectors can deduce that movie and Song have a common parent class mediaitem, so it infers the mediaitem[] class as the type of the library.

let library  = [Movie (name: Span class= "hljs-string" > "Casablanca" , Director:  "Michael Curtiz" ), Song ( Name:  "Blue Suede Shoes" , Artist:  "Elvis Presley" ) , Movie (name:  "citizen Kane" , Director:  "Orson Welles" 
     ), Song (name:  "The One and only" , artist:  "Chesney Haw Kes "), Song (name: " Never Gonna Give You Up ", artist:  "Rick Astley" )]//the type  of   "library"  is  inferred to  be mediaitem[]  

The media items stored in the behind-the-scenes library are still in movie and song types, but if you iterate over it, the instances you take out will be of type Mediaitem instead of the movie and song types.  In order for them to work as their original type, you need to check their types or convert them down to other types, as described below. The Check type (Checking type) uses the type check operator (IS) to check whether an instance belongs to a particular subtype.  If the instance belongs to that subtype, the type check operator returns TRUE, otherwise false is returned. The following example defines two variables, moviecount and songcount, that are used to calculate the number of instances of the Movie and Song types in the array library.

var  moviecount = 0  var  songcount = 0  for  item in  Library {if
      Item is  Movie {++moviecount} else  if  item is  Song {++songcount}}println ( "Media library contains \ (moviecount) movies and \ (songcount) songs" ) //Prints" Media Library contains 2 movies and 3 songs "  

The example iterates over all the items in the array library.  Each time, the for-in loop sets the item to the next Mediaitem in the array. If the current Mediaitem is an instance of a movie type, item is movie returns True and returns false instead. Similarly, item is song checks whether item is an instance of the song type.  At the end of the loop, the values of Moviecount and Songcount are the number of instances that are found to belong to their respective types. Downward transformation (downcasting) a constant or variable of a type may actually belong to a subclass behind the scenes. You can believe that this is the case. You can try to go down to its sub-type, with the type conversion operator because the downward transition may fail, and the type transformation operator takes two different forms. Optional form (optional form) as? Returns an optional value (optional value) of the type you are trying to turn to.  Forced form as takes the attempt to downward transform and force the unpacking (force-unwraps) result as a mixed action. When you are unsure if a downward transition can succeed, use the optional form of type conversion (as?). )。 An optional form of type conversion always returns an optional value (optional value), and the optional value will be nil if the down-turn is not possible.  This allows you to check whether the downward transition is successful. Only use coercion when you can be sure that the downward transformation will succeed.  When you try to move down to an incorrect type, coercion of type conversions triggers a run-time error. The following example iterates through every mediaitem in the library and prints out the appropriate description. To do this, item needs to be really used as a type of movie or song. Not just as a mediaitem.  This is necessary in order to be able to use the Director or artist attribute of movie or song. In this example, each item in the array may be Movie or Song. You don't know the actual type of each item beforehand, so here is the optional form of type conversion (as?). ) to check for each turn in the loop.

 for Item inchLibrary {ifLet movie =Item  as? Movie {println ("Movie: ' \ (movie.name) ', dir. \ (movie.director)")    }Else ifLet song =Item  as? Song {println ("Song: ' \ (Song.name) ', by \ (song.artist)")    }}//Movie: ' Casablanca ', dir. Michael Curtiz//Song: ' Blue Suede Shoes ', by Elvis Presley//Movie: ' Citizen Kane ', dir. Orson Welles//Song: ' The One and only ', by Chesney Hawkes//Song: ' Never Gonna Give you Up ', by Rick Astley

The example first attempts to convert the item to Movie. Because item is an instance of a Mediaitem type, it may be a movie, and again, it may be a Song, or just a base class Mediaitem. Because not sure, the As form will return an optional value when attempting to move down. The return value of item as movie is movie? Type or "optional Movie".
When you convert down to Movie, the app will fail on two Song instances. To handle this, the example above uses an optional binding (optional binding) to check that the optional movie really contains a value (this is to determine if the next turn is successful). Optional bindings are written in this way "if let movie = Item as?" Movie ", you can read this:
"Attempt to convert item to Movie type. If successful, set a new temporary constant movie to store the returned optional movie "
If the downward transformation succeeds, then the movie's properties will be used to print a description of the instance of the movie, including its director's name. When song is found, a similar principle is used to detect the song instance and print its description.
Note: The conversion does not really change the instance or its value. The underlying root instance remains the same, simply using it as the class it is converted to.
  

Type conversions for any and anyobject

Swift provides two special types of aliases for indeterminate types:
Anyobject can represent instances of any class type.
Any can represent any type except the method type (function types).
Note: Use any and anyobject only if you explicitly need its behavior and functionality. It's always better to use the explicit type you expect in your code.

Anyobject type

When you need to work with Cocoa APIs, it generally receives an array of type anyobject[], or "an array of any object type." This is because OBJECTIVE-C does not have an explicit typed array. However, you can often determine the type of object contained in such an array that is provided only from the API information you know.
In these cases, you can use the coerced form of type conversion (AS) to go down each item in the array to a more explicit type than anyobject, which does not require optional parsing (optional unwrapping).
The following example defines an array of type anyobject[] and fills in an instance of three movie types:

let someObjects: AnyObject[] = [    Movie(name"2001: A Space Odyssey""Stanley Kubrick"),    Movie(name"Moon""Duncan Jones"),    Movie(name"Alien""Ridley Scott")]

Knowing that this array contains only movie instances, you can use (as) to go down and unpack to a non-selectable Movie type (PS: It is the normal type that we commonly use, this is to be relative to the optional type).

forobjectin someObjects {    letobjectas Movie    println("Movie: ‘\(movie.name)‘, dir. \(movie.director)")}// Movie: ‘2001: A Space Odyssey‘, dir. Stanley Kubrick// Movie: ‘Moon‘, dir. Duncan Jones// Movie: ‘Alien‘, dir. Ridley Scott

In order to become a shorter form, the lower-someobjects array is the movie[] type instead of the next-to-each-entry method.

forinas Movie[] {    println("Movie: ‘\(movie.name)‘, dir. \(movie.director)")}// Movie: ‘2001: A Space Odyssey‘, dir. Stanley Kubrick// Movie: ‘Moon‘, dir. Duncan Jones// Movie: ‘Alien‘, dir. Ridley Scott
Any type

Here's an example of using any type to work with different types of blending, including non-class types. It creates an array things that can store any type.

var  things = any[] () things.< Span class= "hljs-built_in" >append   (0 ) things. append  ) things. append  ) things. append  ) things. append  ( "hello" ) things. append  (,  5.0 )) things. append  (Movie name:  "Ghostbusters" , Director:  "Ivan Reitman" ))

The things array contains two int values, 2 Double values, 1 String values, one tuple (double, double), and Ivan Reitman the film "Ghostbusters".
You can use the IS and as operators in the switch cases to discover only the types of constants or variables that are known to be any or anyobject. The following example iterates through each item in the things array and finds the type of each item by using the switch statement. The case of these switch statements binds their matching values to a constant of the specified type, allowing them to print their values:

 forThinginchThings {SwitchThing { Case 0  asInt:println ("Zero as an Int") Case 0  asDouble:println ("Zero as a Double") Case  LetSomeint asInt:println ("An integer value of \ (someint)") Case  LetSomedouble asDoublewhereSomedouble >0: println ("a positive double value of \ (somedouble)") Case  isDouble:println ("Some other double value that I don ' t want to print") Case  LetSomestring asString:println ("A string value of \" \ (somestring) \ "") Case  Let(x, Y) as(double, double): println ("An (x, y) point at \ (x), \ (y)") Case  LetMovie asMovie:println ("a movie called ' \ (movie.name) ', dir. \ (movie.director)")default: println ("Something Else")    }}//Zero as an Int//Zero as a Double//An integer value of//A positive double value of 3.14159//A string value of "Hello"//An (x, y) point at 3.0, 5.0//A movie called ' Ghostbusters ', dir. Ivan Reitman

Note: In case of a switch statement, use the coerced type conversion operator (as, not as) to examine and convert to a definite type. This check is always safe in the contents of the switch case statement.

iOS development Language Swift entry---type conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.