swift基础之类多态

原创
2021/04/16 10:15
阅读数 0

多态

//多态
class Media{
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func show() {
        print("name is \(name)")
    }
}

class Movie: Media {
    var director: String
    
    init(name: String, director: String) {
        self.director = director
        super.init(name: name)
    }
    
    override func show() {
        print("movie name is \(name), director is \(director)")
    }
}

class Song: Media {
    var artist: String
    
    init(name: String, artist: String) {
        self.artist = artist
        super.init(name: name)
    }
    
    override func show() {
        print("song name is \(name), artist is \(artist)")
    }
}

let items = [
    Movie(name: "A", director: "B"),
    Song(name: "C", artist: "D")
]
print(type(of: items))
//Array<Media>

向下类型转换 as

//向下类型转换 as
for item in items {
    if let real = item as? Movie {
        real.show()
        //movie name is A, director is B
    }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部