SWIFT4 type conversion, example code

Source: Internet
Author: User

Type conversions
Apple Official Guide Type casting Apple official Guide translation type conversion

Type conversions can be used to determine instance types, as well as instances of the parent class or subclass in the mine hierarchy.

The operators are is and as.

Defining class hierarchies for type conversions
class MediaItem {    var name: String    init(name: String) {        self.name = name    }}class Movie: MediaItem {    var director: String    init(name: String, director: String) {        self.director = director        super.init(name: name)    }}class Song: MediaItem {    var artist: String    init(name: String, artist: String) {        self.artist = artist        super.init(name: name)    }}let library = [    Movie(name: "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 Hawkes"),    Song(name: "Never Gonna Give You Up", artist: "Rick Astley")]// "library" 的类型被推断为[MediaItem]
Type check

The type check operator is to check whether an instance belongs to a particular subclass. is return true, otherwise false is returned.

var movieCount = 0var songCount = 0 for item in library {    if item is Movie {        movieCount += 1    } else if item is Song {        songCount += 1    }} print("Media library contains \(movieCount) movies and \(songCount) songs")// Prints "Media library contains 2 movies and 3 songs"
Down type conversion

The type conversion operator as, or as! , converts its downward type to its subclass type or to its parent class type.

for item in library {    if let movie = item as? Movie {        print("Movie: ‘\(movie.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‘, 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
Type conversions for any and anyobject

Swift provides two special types of aliases for indeterminate types:

    The
    • Anyobject can represent instances of any class type.
    • Any can represent any type, including the function type.
var things = [any] () things.append (0) things.append (0.0) things.append (things.append) 3.14159 ("Hello ") Things.append ((3.0, 5.0)) Things.append (Movie (name:" Ghostbusters ", Director:" Ivan Reitman ")) Things.append ({(name : string), String in "Hello, \ (name)"}) for thing in things {switch thing {case 0 as int:print ("zero As a Int ") case 0 as Double:print (" Zero as a Double ") case-let Someint as Int:print (" an integer val UE of \ (someint)) case let somedouble as double where somedouble > 0:print ("A positive Double value of \ (so medouble) "Double:print" ("Some other Double value that I don ' t want to print") case let somestring a  S String:print ("a String value of \" \ (somestring) \ "") Case let (x, y) as (double, double): print (' An ' (X,     y) point at \ (x), \ (y) ') case let movie as Movie:print ("a movie called \ (Movie.name), dir. \ (movie.director)") Case let Stringconverter as (String)-String:print (Stringconverter ("Michael")) Default:print ("Something Else")}}//zero as an I nt//Zero as a double//an integer value of 42//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//Hello, Michael
let optionalNumber: Int? = 3things.append(optionalNumber)        // Warningthings.append(optionalNumber as Any) // No warning

SWIFT4 type conversion, example code

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.