class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(director: String, name:String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(artist: String, name: String) {
self.artist = artist
super.init(name: name)
}
}
//library被推斷出來存儲的類型是MediaItem類型,因此遍歷時候取出來的每個item類型默認都是MediaItem類型
let library = [
Movie(director: "1", name: "1"),
Song(artist: "2", name: "2"),
Song(artist: "3", name: "3"),
Movie(director: "4", name: "4"),
Song(artist: "5", name: "5"),
]
var movieCount = 0, songCount = 0
for item in library {
//item是MediaItem類型
if item is Movie {
movieCount += 1
}else if item is Song{
songCount += 1
}
}
print("moveCount = \(movieCount) songCount = \(songCount)")
複製代碼
class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(director: String, name:String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(artist: String, name: String) {
self.artist = artist
super.init(name: name)
}
}
//library被推斷出來存儲的類型是MediaItem類型,因此遍歷時候取出來的每個item類型默認都是MediaItem類型
let library = [
Movie(director: "1", name: "1"),
Song(artist: "2", name: "2"),
Song(artist: "3", name: "3"),
Movie(director: "4", name: "4"),
Song(artist: "5", name: "5"),
]
var movieCount = 0
var songCount = 0
for item in library {
//item默認是MediaItem類型
if let _ = item as? Movie{
movieCount += 1
} else if let _ = item as? Song{
songCount += 1
}
}
print("movieCount = \(movieCount) songCount = \(songCount)")
複製代碼
Any與AnyObject區別bash
as,as?,as!函數
class Animal {}
class Dog: Animal {}
/*** as使用場景 ***/
//1. as值類型
var a = 4
let b = a as Int
//2. as向上轉型
var c = Dog()
let d = c as Animal
//3. switch,case匹配對象
switch d {
case _ as Dog :
break
default:
break
}
//4. 消除Any類型警報
var g: Int?
print(g as Any)
var h: Int? = 5
print(h!)
print(h as Any)
/*** as?使用場景 ***/
//1. 向下轉型可能會失敗
var e = d as? Dog
/*** as!使用場景 ***/
//1. 向下轉型確保必定成功
var f = d as! Dog
複製代碼