【问题标题】:Why i'm having the methods of my subclass?为什么我有我的子类的方法?
【发布时间】:2016-05-08 14:48:15
【问题描述】:
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")

【问题讨论】:

    标签: swift class object types


    【解决方案1】:

    song 是您声明为 MediaItem 实例的 Song 实例。一首歌可能是一个媒体项目(通过继承),但一个媒体项目不一定是一首歌。

    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,则不能明确地向下转换 songas 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")
    

    【讨论】:

    • 嘿,我没听懂 :( var song : MediaItem = Song(name: "Mateo",artist: "Romeo") 所以这首歌是 mediaitem 还是 Song?也试图理解英语:(
    • 这是一个Song,你告诉编译器是一个MediaItem。因为你在它的类型上对编译器撒了谎,所以它把它当作一个媒体项目,即使它实际上是一个歌曲实例。
    猜你喜欢
    • 2018-08-22
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2020-02-14
    相关资源
    最近更新 更多