Swift4 基礎(chǔ)部分: Type Casting(類型轉(zhuǎn)換)

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆,基本的語法不作介紹,主要介紹Swift中的一些特性或者與OC差異點(diǎn)。

系列文章:

Type casting is a way to check the type of an instance, or to treat 
that instance as a different superclass or subclass from somewhere 
else in its own class hierarchy.
  • 類型轉(zhuǎn)換可以用來檢測實(shí)例的類型,或者將實(shí)例看成父類或子類的實(shí)例。

為類型轉(zhuǎn)化定義一個類的層級(Defining a Class Hierarchy for Type Casting)

例子:

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")
];

檢查類型(Checking Type)

Use the type check operator (is) to check whether an instance is of a 
certain subclass type.
  • 利用檢查操作符is去檢查實(shí)例是否是一個特定的子類類型。

例子:

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");

執(zhí)行結(jié)果:

Media library contains 2 movies and 3 songs

向下轉(zhuǎn)換(Downcasting)

A constant or variable of a certain class type may actually refer to 
an instance of a subclass behind the scenes. Where you believe this is 
the case, you can try to downcast to the subclass type with a type 
cast operator (as? or as!).
  • 當(dāng)一個常量或變量實(shí)際上是一個子類的實(shí)例時,可以使用as? or as向下轉(zhuǎn)化。

例子:

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("Movie: \(song.name), by \(song.artist)");
    }
}

執(zhí)行結(jié)果:

Media library contains 2 movies and 3 songs
Movie: Casablanca, dir. Michael Curtiz
Movie: Blue Suede Shoes, by Elvis Presley
Movie: Citizen Kane, dir. Orson Welles
Movie: The One And Only, by Chesney Hawkes
Movie: Never Gonna Give You Up, by Rick Astley

AnyAnyObject的類型轉(zhuǎn)換(Type Casting for Any and AnyObject)

Swift provides two special types for working with nonspecific types:

Any can represent an instance of any type at all, including function 
types.

AnyObject can represent an instance of any class type.
  • Any可以表示任何類型的實(shí)例包括函數(shù)類型。
  • Anyobject可以表示任何類類型的實(shí)例。

例子:

var things = [Any]();
things.append(0);
things.append(0.1);
things.append((3.0,5.0));
things.append("hello");

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 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)")
        default:
            print("something else");
    }
}

執(zhí)行結(jié)果:

zero as an Int
a positive double value of 0.1
an (x, y) point at 3.0, 5.0
a string value of "hello"

這里簡單擴(kuò)展一下NSObject,AnyObject,Any的區(qū)別。

例子

class Example{}
class ObjectExample:NSObject{}
var example:Example = Example();
var objectExample:ObjectExample = ObjectExample();
print(example is NSObject);
print(example is AnyObject);
print(objectExample is NSObject);
print(objectExample is AnyObject);

執(zhí)行結(jié)果

false
true
true
true
  • 1.每一個NSObject對象都是AnyObject,單并非每一個AnyObject都是NSObject。
  • 2.NSObjectSwift中需要顯示繼承。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 2016年10月12日 Objective-C id為Swift Any Swift 3接口與Objective-...
    魔靈FH閱讀 2,945評論 0 19
  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young閱讀 4,194評論 1 10
  • 類型轉(zhuǎn)換 可以判斷實(shí)例的類型。 類型轉(zhuǎn)換在 Swift 中使用 is和 as操作符實(shí)現(xiàn)。 類型轉(zhuǎn)換可以檢查一個類型...
    松哥888閱讀 729評論 0 0
  • 本來說好的一星期一篇的我又食言了,現(xiàn)在補(bǔ)上。逼著自己輸出這件事,也不知道跟誰學(xué)會的,痛并快樂著。我的輸入完全來自于...
    內(nèi)有基坑閱讀 498評論 12 2
  • 你知道嗎?我最愛你做自己的樣子。愿你十年后童心還在,好奇心還在。 十年后,你可能不再需要呆在父母的大傘之下,或許你...
    一默閱讀 242評論 4 2

友情鏈接更多精彩內(nèi)容