上QQ阅读APP看书,第一时间看更新
Any and AnyObject
Swift provides two special type aliases to work with non-specific types:
- AnyObject can represent an instance of any class type
- Any can represent an instance of any type, including structs, enumerations, and function types
The Any and AnyObject type aliases must be used only when we explicitly require the behavior and capabilities that they provide. Being precise about the types we expect to work with in our code is a better approach than using the Any and AnyObject types as they can represent any type and pose dynamism instead of safety. Consider the following example:
class Movie {
var director: String
var name: String
init(name: String, director: String) {
self.director = director
self.name = name
}
}
let objects: [AnyObject] = [
Movie(name: "The Shawshank Redemption", director: "Frank Darabont"),
Movie(name: "The Godfather", director: "Francis Ford Coppola")
]
for object in objects {
let movie = object as! Movie
print("Movie: '\(movie.name)', dir. \(movie.director)")
}
// Shorter syntax
for movie in objects as! [Movie] {
print("Movie: '\(movie.name)', dir. \(movie.director)")
}