官术网_书友最值得收藏!

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)")
}
主站蜘蛛池模板: 工布江达县| 武平县| 乃东县| 大冶市| 奉节县| 桃园县| 正蓝旗| 延长县| 平利县| 邛崃市| 寿宁县| 曲麻莱县| 凌云县| 东至县| 门头沟区| 柞水县| 汕尾市| 禄丰县| 荆门市| 恩施市| 万载县| 体育| 古交市| 汶川县| 沂南县| 天峻县| 龙岩市| 大厂| 大田县| 六盘水市| 固镇县| 雷州市| 格尔木市| 离岛区| 灌南县| 扬中市| 阳山县| 和龙市| 诸暨市| 博兴县| 长海县|