Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Type Casting

Swift Type Casting

Type Casting is used to determine the true type of an instance within a class or protocol hierarchy and to use it as another type.

Swift provides is for type checking, as? and as! for downcasting, and type(of:) for obtaining the runtime type.


Preparing a Class Hierarchy

Let's define a class hierarchy used throughout this article: entries in a media library.

Movie, Song, and Audiobook all inherit from the base class MediaItem.

Example

import Foundation

// Base class for library entries

class

MediaItem

{

    var name

:

String

    init

(

name

:

String

)

{

        self.

name

=

name

   

}

}

// Movie

class

Movie

:

MediaItem

{

    var director

:

String

    init

(

name

:

String, director

:

String

)

{

        self.

director

=

director

        super.

init

(

name

:

name

)

   

}

}

// Song

class

Song

:

MediaItem

{

    var artist

:

String

    init

(

name

:

String, artist

:

String

)

{

        self.

artist

=

artist

        super.

init

(

name

:

name

)

   

}

}

// Audiobook

class

Audiobook

:

MediaItem

{

    var narrator

:

String

    init

(

name

:

String, narrator

:

String

)

{

        self.

narrator

=

narrator

        super.

init

(

name

:

name

)

   

}

}

When these instances are placed in the same array, the array's element type is uniformly inferred as [MediaItem].

At this point the compiler only knows that each element is a MediaItem; whether it is specifically a movie or a song must be determined through type casting.

Example

// The static type is [MediaItem], while the actual element types differ

let library

:

[

MediaItem

]

=

[

    Movie

(

name

:

"RUNOOB Programming Primer"

, director

:

"Zhang San"

)

,

    Song

(

name

:

"Newbie's Song"

, artist

:

"Li Si"

)

,

    Movie

(

name

:

"Swift 6 in Action"

, director

:

"Wang Wu"

)

,

    Song

(

name

:

"www.runoob.com"

, artist

:

"RUNOOB Band"

)

,

    Audiobook

(

name

:

"The Definitive Guide to Swift"

, narrator

:

"Zhao Liu"

)

]


Type Checking: is

is only answers "is it of this type?"; it does not extract the instance or perform a conversion.

Swift three type-casting operators: is returns Bool and only checks, as? returns nil on failure, as! crashes directly on failure; the left side shows the MediaItem, Movie, Song class hierarchy, the bottom notes the difference between Any and AnyObject

It returns a Bool, making it best suited to counting, filtering, and similar cases where the specific data does not matter.

Example

var movieCount

=

0

var songCount

=

0

var audiobookCount

=

0

// is only checks; it does not convert

for

item in library

{

   

if

item is Movie

{

        movieCount

=

1

   

}

else

if

item is Song

{

        songCount

=

1

   

}

else

if

item is Audiobook

{

        audiobookCount

=

1

   

}

}

print

(

"(movieCount) movies, (songCount) songs, (audiobookCount) audiobooks"

)

Running the above code produces the following output:



电影 2 部,歌曲 2 首,有声书 1 本

Note:is It checks the runtime type, including subclasses, because Movie inheriting from MediaItem, so movie is MediaItem is also true。


Downcasting: as? and as!

Downcasting means using an instance of a superclass type as a subclass, so that members specific to the subclass can be accessed.

Because a superclass reference may not actually point to that subclass, the conversion can fail, so there are two forms.

Syntax When the conversion fails Return Type Applicable scenarios
as? Return nil Movie? Type uncertain; a safe check is needed
as! Triggers a runtime error; the program crashes Movie The type is known with certainty

In real development, prefer as? together with if let for checking.

Example

// as? returns nil on failure; catch it safely with if let

for

item in library

{

   

if

let movie

=

item as

?

Movie

{

        print

(

"Movie: (movie.name), Director: (movie.director)"

)

   

}

else

if

let song

=

item as

?

Song

{

        print

(

"Song: (song.name), Artist: (song.artist)"

)

   

}

else

if

let audiobook

=

item as

?

Audiobook

{

        print

(

"Audiobook: (audiobook.name), Narrator: (audiobook.narrator)"

)

   

}

}

Running the above code produces the following output:



电影:RUNOOB 编程入门,导演:张三

歌曲:菜鸟之歌,歌手:李四

电影:Swift 6 实战,导演:王五

歌曲:www.runoob.com,歌手:RUNOOB 乐队

有声书:Swift 权威指南,朗读者:赵六

When a position is known to hold a movie, as! can retrieve a non-optional result in one step.

Example

// The first item is known to be a movie; cast directly with as!

let first

=

library

[

0

]

as

!

Movie

print

(

"The first item is a movie: (first.name)"

)

// A safer approach: check first, then cast

if

let second

=

library

[

1

]

as

?

Song

{

    print

(

"The second item is a song: (second.artist)"

)

}

Running the above code produces the following output:



第一条是电影:RUNOOB 编程入门

第二条是歌曲:李四

Note:If both the as! If the target type is wrong, the program terminates immediately and prints something like Could not cast value of type 'Song' to 'Movie'. a runtime error. This error cannot be caught with do-catch so use it only when failure is logically impossible. as!。


Upcasting and as

Treating a subclass instance as a superclass is called upcasting; it always succeeds, so no question mark or exclamation mark is needed.

In most cases a direct assignment suffices and the compiler handles it automatically; when the type must be stated explicitly, you can write as.

Example

let movie

=

Movie

(

name

:

"RUNOOB Documentary"

, director

:

"Zhang San"

)

// Implicit upcasting

let item

:

MediaItem

=

movie

// Writing as explicitly has the same effect

let explicitItem

=

movie as MediaItem

print

(

"Implicit: (item.name)"

)

print

(

"Explicit: (explicitItem.name)"

)

// After upcasting, subclass-specific members are not visible

// print(item.director) // Compile error: MediaItem has no director

if

let backToMovie

=

item as

?

Movie

{

    print

(

"Cast back to access the director: (backToMovie.director)"

)

}

Running the above code produces the following output:



隐式:RUNOOB 纪录片

显式:RUNOOB 纪录片

转型回来才能访问导演:张三

Upcasting merely means "viewing the same object through a broader type"; the instance itself does not change and no copy is made.


Getting the Runtime Type with type(of:)

type(of:) returns the dynamic type of a value and is the tool most commonly used for debugging and dynamic dispatch.

Note that its parameter carries a label, written type(of: item); the old technique of taking a property to obtain the type has been removed and should no longer be used.

Example

// The static type of the variables is all MediaItem, but their runtime types differ

for

item in library

{

    print

(

"Runtime type: (type(of: item))"

)

}

Running the above code produces the following output:



运行时类型:Movie

运行时类型:Song

运行时类型:Movie

运行时类型:Song

运行时类型:Audiobook

The return type is MediaItem.Type, a metatype value that can be used for comparison.

Example

let item

=

library

[

0

]

// Compare metatypes

if

type

(

of

:

item

)

==

Movie.

self

{

    print

(

"This item is a movie"

)

}

// You can also print the metatype's description directly

print

(

"Type name: (type(of: item))"

)

print

(

"Static type: (MediaItem.self)"

)

Running the above code produces the following output:



这一条是电影

类型名:Movie

静态类型:MediaItem

Note:type(of:) retrieves the runtime type,MediaItem.self retrieves the static type written in the code; do not confuse the two.


Any and AnyObject

Any represents "a value of any type," including structs, enums, functions, and closures.

AnyObject represents "an instance of any class type," which is narrower in scope than Any.

Type What Can It Hold Typical use
Any Any type: classes, structs, enums, functions, tuples Mixed containers, interoperability with dynamic languages
AnyObject Only class instances With Objective-C's id Corresponds to

When extracting values from Any, using switch with as to match case by case is the clearest approach.

Example

var things

:

[

Any

]

=

[

]

things.

append

(

0

)

                                           

// Int

things.

append

(

0.0

)

                                         

// Double

things.

append

(

42

)

                                         

// Int

things.

append

(

3.14159

)

                                     

// Double

things.

append

(

"hello runoob"

)

                             

// String

things.

append

(

(

3.0

,

5.0

)

)

                                 

// Tuple

things.

append

(

Movie

(

name

:

"RUNOOB Documentary"

, director

:

"Zhang San"

)

)

// Class instance

things.

append

(

{

(

name

:

String

)

String in

"Hello, (name)"

}

)

// Closure

for

thing in things

{

   

switch

thing

{

   

case

let someInt as Int

:

        print

(

"Integer: (someInt)"

)

   

case

let someDouble as Double where someDouble

0

:

        print

(

"Positive float: (someDouble)"

)

   

case

let someString as String

:

        print

(

"String: (someString)"

)

   

case

let

(

x, y

)

as

(

Double, Double

)

:

        print

(

"Tuple: (x), (y)"

)

   

case

let movie as Movie

:

        print

(

"Movie: (movie.name)"

)

   

case

let stringConverter as

(

String

)

String

:

        print

(

stringConverter

(

"RUNOOB"

)

)

   

default

:

        print

(

"other"

)

   

}

}

Running the above code produces the following output:



整数:0

其他

整数:42

正浮点数:3.14159

字符串:hello runoob

元组:3.0, 5.0

电影:RUNOOB 纪录片

Hello, RUNOOB

The second element is 0.0 because where someDouble > 0 does not hold and it falls into the default branch.

AnyObject is used similarly, except that elements must be class instances.

Example

let objects

:

[

AnyObject

]

=

[

    Movie

(

name

:

"Runoob Tutorial"

, director

:

"RUNOOB"

)

,

    Song

(

name

:

"Song of RUNOOB"

, artist

:

"Newbie Band"

)

]

for

object in objects

{

    print

(

"AnyObject actual type: (type(of: object))"

)

}

Running the above code produces the following output:



AnyObject 实际类型:Movie

AnyObject 实际类型:Song

Note:Do not put an optional value directly into [Any], Swift issues a expression implicitly coerced from 'Int?' to 'Any' warning, because the optional is wrapped as an Optional before being stored. If you really need to store it, unwrap it first or write it explicitly as as Any。


Conversion of the Existential Type any P

A protocol type is now written any Protocol, meaning "any type that conforms to the protocol."

Through any P you can access only the members declared in the protocol; to access members unique to the concrete type, you likewise need to downcast.

Example

// Protocol: any type that can provide a description

protocol Describable

{

    var summary

:

String

{

get

}

}

extension Movie

:

Describable

{

    var summary

:

String

{

return

"Movie '(name)', director (director)"

}

}

extension Song

:

Describable

{

    var summary

:

String

{

return

"Song '(name)', artist (artist)"

}

}

// Array of existential type: the static type of the elements is any Describable

let describables

:

[

any Describable

]

=

[

    Movie

(

name

:

"RUNOOB Programming Primer"

, director

:

"Zhang San"

)

,

    Song

(

name

:

"Newbie's Song"

, artist

:

"Li Si"

)

]

for

item in describables

{

    print

(

item.

summary

)

               

// Members required by the protocol are directly usable

   

if

let movie

=

item as

?

Movie

{

   

// Downcast back to the concrete type

        print

(

"This is a movie, directed by (movie.director)"

)

   

}

else

if

let song

=

item as

?

Song

{

        print

(

"This is a song, by (song.artist)"

)

   

}

    print

(

"Actual type: (type(of: item))"

)

}

Running the above code produces the following output:



电影《RUNOOB 编程入门》,导演 张三

这是电影,导演是 张三

实际类型:Movie

歌曲《菜鸟之歌》,歌手 李四

这是歌曲,歌手是 李四

实际类型:Song

Converting from a concrete type to any P is implicit because the compiler can confirm it conforms to the protocol.

Conversely, converting from any P to a concrete type must be written explicitly with as? or as!, because the runtime type is not necessarily that type.


Common questions

The following questions are where mistakes are most common in type casting.

When should is be used, and when should as? be used?

Use is when you only want to know the type and do not need to access members.

Use as? when you need the converted instance and want to access subclass members.

Can as? and as! be interchanged?

No. Replacing as! with as? merely swaps a crash for a nil return, which requires extra handling of the nil branch.

Conversely, replacing as? with as! turns a safe check into a potential crash; do not do this unless it is logically certain to succeed.

Why does item as? Movie return nil for some elements?

Because downcasting checks the runtime type and succeeds only when the element really is a Movie or a subclass of it.

When the array contains a Song, performing as? Movie on it naturally yields nil.

Is type casting in Swift the same as in Objective-C?

The idea is similar, but Swift's as? and as! distinguish "may fail" from "certain to succeed," making them clearer than Objective-C's isKindOfClass:.

When interoperating with Objective-C, AnyObject roughly corresponds to id, while Any has no direct counterpart.