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)
}
}
var song : MediaItem = Song(name: "Mateo",artist: "Romeo")
我理解这首歌是MediaItem
个实例,但我正在用Song
个实例初始化它。
我的歌是什么类型的?是MediaItem
还是Song
?
我应该使用哪种方法?
var song : MediaItem = Song(name: "Mateo",artist: "Romeo")
或
var song = Song(name: "Mateo",artist: "Romeo")
答案 0 :(得分:2)
song
是您声明为Song
实例的MediaItem
实例。歌曲可以是媒体项目(通过继承),但媒体项目不一定是歌曲。
var song : MediaItem = Song(name: "Mateo",artist: "Romeo")
song.dynamicType // Song.Type
song is Song // true
song is MediaItem // true
song is Movie // false
song.name // "Mateo"
song.artist // Value of Type 'MediaItem' has no member 'artist'
将其声明为MediaItem
时的“问题”是,如果不强制转发as explained on the Swift blog
song as Song // raises the error "'MediaItem' is not convertible to 'Song'; did you mean to use 'as!' to force downcast?"
song as! Song // forced downcast is allowed
类型推断是首选方法;它更具可读性和简洁性:
var song = Song(name: "Mateo",artist: "Romeo")