19.类型转换

  类型转换在 Swift 中使用 is as 操作符实现。is用于判断实例的类型,as用于转换实例的类型。

1.从一个示例谈起 

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")
];

//检查类型:用类型检查操作符(is)来检查一个实例是否属于特定子类型。若实例属于那个子类型,类型检查操作符返回 true,否则返回 false。
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 library contains \(movieCount) movies and \(songCount) songs");  //"Media library contains 2 movies and 3 songs\n"

//向下转型:某类型的一个常量或变量可能在幕后实际上属于一个子类。当确定是这种情况时,你可以尝试向下转到它的子类型,用类型转换操作符(as? 或 as!)。
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
 */

2.Any AnyObject 的类型转换

  Swift 为不确定类型提供了两种特殊的类型别名:

  1. AnyObject:可以表示任何类类型的实例。
  2. Any:可以表示任何类型,包括函数类型。
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);
    }
}

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

for movie in someObjects as! [Movie] {
    print("Movie: '\(movie.name)', dir. \(movie.director)");
}

/*
 打印结果:
 Movie: '2001: A Space Odyssey', dir. Stanley Kubrick
 Movie: 'Moon', dir. Duncan Jones
 Movie: 'Alien', dir. Ridley Scott
 */

var things = [Any]();

things.append(0);
things.append(0.0);
things.append("Hello World");

print("\(things)");  //[0, 0.0, "Hello World"]

 

posted @ 2016-07-18 20:33  LeeGof  阅读(148)  评论(0编辑  收藏  举报