Swift4类型转换
程序员文章站
2024-02-20 15:03:40
...
Swift 中类型转换的实现为 is
(类型检查) 和 as
(类型转化) 操作符。这两个操作符使用了一种简单传神的方式来检查一个值的类型或将某个值转换为另一种类型。
// 定义父类
class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
// 定义子类
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
// 创建Library数组存储
let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// "library" 的类型被推断为[MediaItem]
事实上 library
储存的项目在后台依旧是 Movie
和 Song
实例。总之,如果你遍历这个数组的内容,你取出的项目将会是 MediaItem
类型而非 Movie
或 Song
类型。为了使用他们原生的类型,你需要检查他们的类型或将他们向下转换为不同的类型。
使用类型检查
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
使用向下类型转换
for item in library {
if let movie = item as? Movie {
print("Movie: '\(movie.name)', dir. \(movie.director)")
} else if let song = item as? Song {
print("Song: '\(song.name)', by \(song.artist)")
}
}
Any 和 AnyObject 的类型转换
Swift 为不确定的类型提供了两种特殊的类型别名:
-
AnyObject
: 可以表示任何类 类型的实例 -
Any
: 可以表示任何类型,包括函数类型
var things = [Any]()
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things.append({ (name: String) -> String in "Hello, \(name)" })
// 使用
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double:
print("zero as a Double")
case let someInt as Int:
print("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
print("a positive double value of \(someDouble)")
case is Double:
print("some other double value that I don't want to print")
case let someString as String:
print("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
print("an (x, y) point at \(x), \(y)")
case let movie as Movie:
print("a movie called \(movie.name), dir. \(movie.director)")
case let stringConverter as (String) -> String:
print(stringConverter("Michael"))
default:
print("something else")
}
}
上一篇: ps制作喜庆的迎新春的背景
下一篇: Swift4 集合类型