为什么我有我的子类的方法?

时间:2016-01-30 23:59:43

标签: swift class object types

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

1 个答案:

答案 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 >

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