<p><em>Type casting</em> is a way to check the type of an instance, and/or to treat that instance as if it is a different superclass or subclass from somewhere else in its own class hierarchy.</p>
<p> Type casting in Swift is implemented with the <code>is</code> and <code>as</code> operators. These two operators provide a simple and expressive way to check the type of a value or cast a value to a different type.</p>
<p> 你也可以用来检查一个类是否实现了某个协议,就像在 <ahref="Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-XID_363">Protocols》Checking for Protocol Conformance</a>部分讲述的一样。</p>
<p> You can also use type casting to check whether a type conforms to a protocol, as described in <spanclass="x-name"><ahref="Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-XID_363">Checking for Protocol Conformance</a></span>.</p>
<h3id="-defining-a-class-hierarchy-for-type-casting">定义一个类层次作为例子Defining a Class Hierarchy for Type Casting</h3>
<p> You can use type casting with a hierarchy of classes and subclasses to check the type of a particular class instance and to cast that instance to another class within the same hierarchy. The three code snippets below define a hierarchy of classes and an array containing instances of those classes, for use in an example of type casting.</p>
<p> The first snippet defines a new base class called <code>MediaItem</code>. This class provides basic functionality for any kind of item that appears in a digital media library. Specifically, it declares a <code>name</code> property of type <code>String</code>, and an <code>init name</code> initializer. (It is assumed that all media items, including all movies and songs, will have a name.)</p>
<p> The next snippet defines two subclasses of <code>MediaItem</code>. The first subclass, <code>Movie</code>, encapsulates additional information about a movie or film. It adds a <code>director</code> property on top of the base <code>MediaItem</code> class, with a corresponding initializer. The second subclass, <code>Song</code>, adds an <code>artist</code> property and initializer on top of the base class:</p>
<p> The final snippet creates a constant array called <code>library</code>, which contains two <code>Movie</code> instances and three <code>Song</code> instances. The type of the <code>library</code> array is inferred by initializing it with the contents of an array literal. Swift’s type checker is able to deduce that <code>Movie</code> and <code>Song</code> have a common superclass of <code>MediaItem</code>, and so it infers a type of <code>MediaItem[]</code> for the <code>library</code> array:</p>
<p> The items stored in <code>library</code> are still <code>Movie</code> and <code>Song</code> instances behind the scenes. However, if you iterate over the contents of this array, the items you receive back are typed as <code>MediaItem</code>, and not as <code>Movie</code> or <code>Song</code>. In order to work with them as their native type, you need to <em>check</em> their type, or <em>downcast</em> them to a different type, as described below.</p>
<p> Use the <em>type check operator</em> (<code>is</code>) to check whether an instance is of a certain subclass type. The type check operator returns <code>true</code> if the instance is of that subclass type and <code>false</code> if it is not.</p>
<p> The example below defines two variables, <code>movieCount</code> and <code>songCount</code>, which count the number of <code>Movie</code> and <code>Song</code> instances in the <code>library</code> array:</p>
<pre><code>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"
<p> This example iterates through all items in the <code>library</code> array. On each pass, the <code>for</code>-<code>in</code> loop sets the <code>item</code> constant to the next <code>MediaItem</code> in the array.</p>
<p> 若当前 <code>MediaItem</code> 是一个 <code>Movie</code> 类型的实例, <code>item is Movie</code> 返回 <code>true</code>,相反返回 <code>false</code>。同样的,<code>item is Song</code>检查item是否为<code>Song</code>类型的实例。在循环末尾,<code>movieCount</code> 和 <code>songCount</code>的值就是被找到属于各自的类型的实例数量。</p>
<p><code>item is Movie</code> returns <code>true</code> if the current <code>MediaItem</code> is a <code>Movie</code> instance and <code>false</code> if it is not. Similarly, <code>item is Song</code> checks whether the item is a <code>Song</code> instance. At the end of the <code>for</code>-<code>in</code> loop, the values of <code>movieCount</code> and <code>songCount</code> contain a count of how many <code>MediaItem</code> instances were found of each type.</p>
<p> A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to <em>downcast</em> to the subclass type with the <em>type cast operator</em> (<code>as</code>).</p>
<p> Because downcasting can fail, the type cast operator comes in two different forms. The optional form, <code>as?</code>, returns an optional value of the type you are trying to downcast to. The forced form, <code>as</code>, attempts the downcast and force-unwraps the result as a single compound action.</p>
<p> Use the optional form of the type cast operator (<code>as?</code>) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be <code>nil</code> if the downcast was not possible. This enables you to check for a successful downcast.</p>
<p> Use the forced form of the type cast operator (<code>as</code>) only when you are sure that the downcast will always succeed. This form of the operator will trigger a runtime error if you try to downcast to an incorrect class type.</p>
<p> The example below iterates over each <code>MediaItem</code> in <code>library</code>, and prints an appropriate description for each item. To do this, it needs to access each item as a true <code>Movie</code> or <code>Song</code>, and not just as a <code>MediaItem</code>. This is necessary in order for it to be able to access the <code>director</code> or <code>artist</code> property of a <code>Movie</code> or <code>Song</code> for use in the description.</p>
<p> In this example, each item in the array might be a <code>Movie</code>, or it might be a <code>Song</code>. You don’t know in advance which actual class to use for each item, and so it is appropriate to use the optional form of the type cast operator (<code>as?</code>) to check the downcast each time through the loop:</p>
<pre><code>for item in library {
if let movie = item as? Movie {
println("Movie: '\(movie.name)', dir. \(movie.director)")
} else if let 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
<p> The example starts by trying to downcast the current <code>item</code> as a <code>Movie</code>. Because <code>item</code> is a <code>MediaItem</code> instance, it’s possible that it <em>might</em> be a <code>Movie</code>; equally, it’s also possible that it might a <code>Song</code>, or even just a base <code>MediaItem</code>. Because of this uncertainty, the <code>as?</code> form of the type cast operator returns an <em>optional</em> value when attempting to downcast to a subclass type. The result of <code>item as Movie</code> is of type <code>Movie?</code>, or “optional <code>Movie</code>”.</p>
<p> 当应用在两个<code>Song</code>实例时,下转为 <code>Movie</code> 失败。为了处理这种情况,上面的实例使用了可选绑定(optional binding)来检查optional <code>Movie</code>真的包含一个值(这个是为了判断下转是否成功。)可选绑定是这样写的“<code>if let movie = item as? Movie</code>”,可以这样解读:</p>
<p> Downcasting to <code>Movie</code> fails when applied to the two <code>Song</code> instances in the library array. To cope with this, the example above uses optional binding to check whether the optional <code>Movie</code> actually contains a value (that is, to find out whether the downcast succeeded.) This optional binding is written “<code>if let movie = item as? Movie</code>”, which can be read as:</p>
<p> “Try to access <code>item</code> as a <code>Movie</code>. If this is successful, set a new temporary constant called <code>movie</code> to the value stored in the returned optional <code>Movie</code>.”</p>
<p> If the downcasting succeeds, the properties of <code>movie</code> are then used to print a description for that <code>Movie</code> instance, including the name of its <code>director</code>. A similar principle is used to check for <code>Song</code> instances, and to print an appropriate description (including <code>artist</code> name) whenever a <code>Song</code> is found in the library.</p>
<pre><code>注意
转换没有真的改变实例或它的值。潜在的根本的实例保持不变;只是简单地把它作为它被转换成的类来使用。
NOTE
Casting does not actually modify the instance or change its values. The underlying instance remains the same; it is simply treated and accessed as an instance of the type to which it has been cast.
</code></pre><h3id="any-anyobject-type-casting-for-any-and-anyobject">Any和AnyObject的转换 Type Casting for Any and AnyObject</h3>
Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.
<p> When working with Cocoa APIs, it is common to receive an array with a type of <code>AnyObject[]</code>, or “an array of values of any object type”. This is because Objective-C does not have explicitly typed arrays. However, you can often be confident about the type of objects contained in such an array just from the information you know about the API that provided the array.</p>
<p> In these situations, you can use the forced version of the type cast operator (<code>as</code>) to downcast each item in the array to a more specific class type than <code>AnyObject</code>, without the need for optional unwrapping.</p>
<p> The example below defines an array of type <code>AnyObject[]</code> and populates this array with three instances of the <code>Movie</code> class:</p>
<pre><code>let someObjects: AnyObject[] = [
Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"),
<p> Because this array is known to contain only <code>Movie</code> instances, you can downcast and unwrap directly to a non-optional <code>Movie</code> with the forced version of the type cast operator (<code>as</code>):</p>
<pre><code>for object in someObjects {
let movie = object as Movie
println("Movie: '\(movie.name)', dir. \(movie.director)")
}
// Movie: '2001: A Space Odyssey', dir. Stanley Kubrick
<p> For an even shorter form of this loop, downcast the <code>someObjects</code> array to a type of <code>Movie[]</code> instead of downcasting each item:</p>
<pre><code>for movie in someObjects as Movie[] {
println("Movie: '\(movie.name)', dir. \(movie.director)")
}
// Movie: '2001: A Space Odyssey', dir. Stanley Kubrick
<p> Here’s an example of using <code>Any</code> to work with a mix of different types, including non-class types. The example creates an array called <code>things</code>, which can store values of type <code>Any</code>:</p>
<p> The <code>things</code> array contains two <code>Int</code> values, two <code>Double</code> values, a <code>String</code> value, a tuple of type <code>(Double, Double)</code>, and the movie “Ghostbusters”, directed by Ivan Reitman.</p>
<p> You can use the <code>is</code> and <code>as</code> operators in a <code>switch</code> statement’s cases to discover the specific type of a constant or variable that is known only to be of type <code>Any</code> or <code>AnyObject</code>. The example below iterates over the items in the <code>things</code> array and queries the type of each item with a <code>switch</code> statement. Several of the <code>switch</code> statement’s cases bind their matched value to a constant of the specified type to enable its value to be printed:</p>
<pre><code>for thing in things {
switch thing {
case 0 as Int:
println("zero as an Int")
case 0 as Double:
println("zero as a Double")
case let someInt as Int:
println("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
println("a positive double value of \(someDouble)")
case is Double:
println("some other double value that I don't want to print")
case let someString as String:
println("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
println("an (x, y) point at \(x), \(y)")
case let movie as Movie:
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 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
</code></pre><p>。</p>
<pre><code>注意
在一个switch语句的case中使用强制形式的类型检查操作符(as, 而不是 as?) 来检查和转换到一个规定的类型。在switch case 语句的内容中这种检查总是安全的。
NOTE
The cases of a switch statement use the forced version of the type cast operator (as, not as?) to check and cast to a specific type. This check is always safe within the context of a switch case statement.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.