protocol P : class {
var value:Int {get}
}
class X : P {
var value = 0
init(_ value:Int) {
self.value = value
}
}
var ps:[P] = [X(1), X(2)]
for p in ps {
if let x = p as? X { // works for a single variable
...
}
}
if let xs = ps as? [X] { // doesn't work for an array (EXC_BAD_ACCESS)
...
}
If P is a class instead of a protocol, than the code works correctly. What's the difference between class and protocol? They're both implemented as pointers in the heap, aren't they? The above code can be compiled successfully, but crash at runtime. What does this EXC_BAD_ACCESS error mean?
Thanks to @Antonio, but I still don't understand how this sample code works.
let someObjects: [AnyObject] = [
Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"),
Movie(name: "Moon", director: "Duncan Jones"),
Movie(name: "Alien", director: "Ridley Scott")
]
for movie in someObjects as [Movie] {
println("Movie: '\(movie.name)', dir. \(movie.director)")
}
Is AnyObject a special case?
protocol P {
}
@objc class X : P {
}
@objc class Y : X {
}
var xs:[X] = [Y(), Y()]
var ps:[P] = [Y(), Y()]
xs as? [Y] // works
ps as? [Y] // EXC_BAD_ACCESS
I tried this code in playground. Since this is pure swift code, I think it has nothing to do with @objc.