Swift4 基礎部分: Type Casting(類型轉換)

本文是學習《The Swift Programming Language》整理的相關隨筆,基本的語法不作介紹,主要介紹Swift中的一些特性或者與OC差異點。

系列文章:

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.
  • 類型轉換可以用來檢測實例的類型,或者將實例看成父類或子類的實例。

為類型轉化定義一個類的層級(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去檢查實例是否是一個特定的子類類型。

例子:

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

執行結果:

Media library contains 2 movies and 3 songs

向下轉換(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!).
  • 當一個常量或變量實際上是一個子類的實例時,可以使用as? or as向下轉化。

例子:

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

執行結果:

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的類型轉換(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可以表示任何類型的實例包括函數類型。
  • Anyobject可以表示任何類類型的實例。

例子:

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

執行結果:

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"

這里簡單擴展一下NSObject,AnyObject,Any的區別。

例子

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

執行結果

false
true
true
true
  • 1.每一個NSObject對象都是AnyObject,單并非每一個AnyObject都是NSObject
  • 2.NSObjectSwift中需要顯示繼承。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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