//: Playground - noun: a place where people can play
import UIKit
// # 為類型轉(zhuǎn)換定義類層次
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)
}
}
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].而事實(shí)上,library存儲的項(xiàng)目在后臺依舊是各自的類型的實(shí)例.但是遍歷這個(gè)數(shù)組取出的將會是MediaItem類型
// # 類型檢查
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
print("Media library contains \(movieCount) movies and \(songCount) songs")
library[0] is MediaItem
// another example
var controller = UITableViewController()
controller is CustomDebugStringConvertible
// # 向下類型轉(zhuǎn)換
// as 用于消除二義性
let num1 = 42 as CGFloat
let num2 = 42 as Int
let num3 = 42 as Double
class Animal {}
class Cat: Animal {}
let cat = Cat()
let animal = cat as Animal // as is used to make an instance become its father class instance--this will never fail.
let kitty = animal as! Cat // as! is used to downcast a father instance--this can fail.
// as & protocol
protocol Facial {
var faceSize: Double { get set }
}
class Human: Facial {
var faceSize: Double = 1
}
class Dog: Facial {
var faceSize: Double = 0.5
}
let creatureOne: Facial = Human()
let humanOne = creatureOne as! Human
let creatureTwo = humanOne as Facial
// as?返回可選項(xiàng),as!強(qiáng)制轉(zhuǎn)換
// 情況1: 左操作數(shù)非可選,存疑在于其能不能進(jìn)行轉(zhuǎn)換
for item in library {
if let movie = item as? Movie {
print("Movie: '\(movie.name)', director \(movie.director)")
} else if let song = item as? Song {
print("Song: '\(song.name)', by \(song.artist)")
}
}
// 情況2: 左操作數(shù)是可選,存疑在于存不存在以及存在時(shí)能不能轉(zhuǎn)換
var itemMaybe: MediaItem? = Movie(name: "I Love You", director: "Berg")
let songMaybe = itemMaybe as? Song
let movieMaybe = itemMaybe as? Movie
let movieMaybeTwo = itemMaybe as! Movie
// 注意:也可以將類轉(zhuǎn)化為基類,但是基類仍然保留了子類數(shù)據(jù)
let movie = Movie(name: "Casablanca", director: "Michael Curtiz")
let ss = movie as MediaItem
ss as? Movie
// # Any和AnyObject的類型轉(zhuǎn)換
// AnyObject 可以表示任何類類型實(shí)例
// Any 可以表示任何類型,包括函數(shù)類型
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)" })
// trick: is 和 as 靈活使用
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")
}
}
let optionalNumber: Int? = 3
things.append(optionalNumber) // Warning
things.append(optionalNumber as Any) // No warning
// 返回不同的類型
func function() -> MediaItem {
return Movie(name: "Whatever", director: "Kevin")
}
let some = function()
some.name
let dd = some as! Movie
dd.director
18.類型轉(zhuǎn)換 Type Casting Swift官方文檔——版納的筆記
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 原文閱讀:《算法(第四版)》第一章 第一節(jié):基礎(chǔ)編程模型 有沒有在面試的時(shí)候被問到:下面這幾行代碼的執(zhí)行結(jié)果是什么...
- 小學(xué)語文修改病句的方法 修改病句是小學(xué)語文考試中常見的題型,在修改病句之前,我們應(yīng)該清晰的了解有哪些病句現(xiàn)象,下面...
- 【Swift 3.1】19 - 類型轉(zhuǎn)換 (Type Casting) 自從蘋果2014年發(fā)布Swift,到現(xiàn)在已...
- 類型轉(zhuǎn)換 可以判斷實(shí)例的類型。 類型轉(zhuǎn)換在 Swift 中使用 is和 as操作符實(shí)現(xiàn)。 類型轉(zhuǎn)換可以檢查一個(gè)類型...
- “堅(jiān)持”和“毅力“是并不存在的概念,已經(jīng)把它們從操作系統(tǒng)中剔除掉了。為什么有毅力和堅(jiān)持是從來沒有持續(xù)做好一件事。...