- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 171字
- 2021-07-02 23:54:29
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)")
}
推薦閱讀
- Python絕技:運用Python成為頂級數據工程師
- 數據可視化:從小白到數據工程師的成長之路
- 企業大數據系統構建實戰:技術、架構、實施與應用
- OracleDBA實戰攻略:運維管理、診斷優化、高可用與最佳實踐
- Python金融實戰
- SQL優化最佳實踐:構建高效率Oracle數據庫的方法與技巧
- 金融商業算法建模:基于Python和SAS
- 數據中心數字孿生應用實踐
- Flutter Projects
- 云原生數據中臺:架構、方法論與實踐
- Oracle RAC日記
- R Object-oriented Programming
- openGauss數據庫核心技術
- 實現領域驅動設計
- 企業大數據處理:Spark、Druid、Flume與Kafka應用實踐