Swift学习笔记-类型转换

1.判断是否为某类型用 is

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")
        ]
        
        var movieCount = 0
        var songCount = 0
        
        for item in library {
            if item is Movie{
                movieCount += 1
            }else if item is Song{
                songCount += 1
            }
        }
        
        print("There are \(movieCount) moviewsm, \(songCount) songs")

2.向下转型用 is

不确定是否成功用 is? 强制转换用 is!

for item in library {
            if let movie = item as? Movie{
                print("movie named:\(movie.name)")
            }else if let song = item as? Song{
                print("song named:\(song.name)")
            }
        }

3.Any 和 AnyObject的类型转换

  • Any可以表示任何类型,包括函数类型。
  • AnyObject可以表示任何类类型的实例。
    如果想用

重要
let optionalNumber: Int? = 3
things.append(optionalNumber) // 警告
things.append(optionalNumber as Any) // 没有警告

你可能感兴趣的:(Swift学习笔记-类型转换)