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

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)")
}
主站蜘蛛池模板: 弋阳县| 梁平县| 那曲县| 曲阳县| 九江市| 万盛区| 高密市| 县级市| 建始县| 上栗县| 海兴县| 军事| 宾阳县| 句容市| 衡南县| 正安县| 淮北市| 四子王旗| 施甸县| 平罗县| 闽清县| 望谟县| 独山县| 花垣县| 沭阳县| 静乐县| 三原县| 安塞县| 莫力| 电白县| 兴安县| 赣州市| 门源| 曲松县| 铜山县| 弥渡县| 松桃| 明水县| 防城港市| 鲁甸县| 安顺市|