Apple给我们提供了一个向下转换同类型对象的示例:
let someObjects: [AnyObject] = [
Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"),
Movie(name: "Moon", director: "Duncan Jones"),
Movie(name: "Alien", director: "Ridley Scott")
]
然后我们可以通过创建一个抽象变量" object"来访问每个单独的属性。并按照我们的预期(电影)投射它:
for object in someObjects {
let movie = object as! Movie
print("Movie: '\(movie.name)', dir. \(movie.director)")
}
但是如果我们进入下一个级别,例如我们有电影的子类:
无声电影
喜剧
动作
每个都具有相同的属性 - 名称&导演
我试图以与上面作为电影"因为我假设是一个父类,它能够识别它的子类,但当然这没有用,否则这个问题就不存在了!
答案 0 :(得分:1)
我理解你的问题是正确的。因此,转换对子类的工作方式与示例相同。也许你错过了一些东西(提示在代码注释中):
// here the subclass SilentFilm
class SilentFilm:Movie {
}
// Here the array with SilentFilm objects
let someOtherObjects: [AnyObject] = [
SilentFilm(name: "silentname", director: "silentdirector"),
SilentFilm(name: "silentname2", director: "silentdirector2")
]
for object2 in someOtherObjects {
// Here the cast to Movie like in your example
let movie = object2 as! Movie
// or cast to SilentFilm works also
// let movie = object2 as! SilentFilm
print("Movie: '\(movie.name)', dir. \(movie.director)")
}
// Expected Output
// Movie: 'silentname', dir. silentdirector
// Movie: 'silentname2', dir. silentdirector2
如果我错过了你的问题,请纠正我!
答案 1 :(得分:0)
为什么不创建具有父Movie
类的类层次结构,并在迭代数组时检查电影的类型?如果您指定数组包含AnyObject
个对象,并且所有子类型都继承自Movie
,则无需强制从Movie
进行强制转换。
class Movie {
var name: String!
var director: String!
init(name: String, director: String) {
self.name = name
self.director = director
}
}
class Comedy: Movie {
var laughTrack: Bool!
init(name: String, director: String, laughTrack: Bool) {
super.init(name: name, director: director)
self.laughTrack = laughTrack
}
}
let someObjects: [Movie] = [
Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"),
Movie(name: "Moon", director: "Duncan Jones"),
Movie(name: "Alien", director: "Ridley Scott"),
Comedy(name: "Caddyshack", director: "Harold Ramis", laughTrack: false)
]
for movie in someObjects {
if movie is Comedy {
print("\(movie.name) is a comedy")
} else {
print("\(movie.name) is a movie")
}
}
输出:
2001:太空漫游是一部电影
月亮是一部电影
外星人是一部电影
Caddyshack是一部喜剧