2015-10-22 37 views
0

在swift 2.0中,有一種方法可以將類的類型傳遞給變量,以便稍後可以使用它來檢查對象類型是否爲該類類型。 通過以下示例更好地解釋:在變量中傳遞類類型

class Base {..} 
class Derived : Base {..} 
var obj: Base = Derived() 
if obj is Derived { 
    print("obj is Derived type") 
} 

這很好。但我想是存儲類類型變量的東西「衍生」這樣的能力:

let classType = Derived // Of course this will give compile error 

而且使用它後,檢查對象的類型:

if obj is classType {..} 

最近我前來處理節省類類型是:

let classType = Derived.self 

這是說此類類別的類型爲「Derived.Type」,但你真的不能使用檢查對象鍵入如下:

if obj is classType {..blah.. } // Compile error.'Use of undeclared type 'classType' 

我希望你明白我的觀點。我試圖將類類型存儲在變量中,並稍後使用它來檢查對象是否屬於該類型。 有沒有辦法做到這一點。 我看着堆棧溢出類似的論壇,但沒有接近回答這個問題。

回答

2

像這樣:

class Base {} 
    class Derived : Base {} 
    var obj: Base = Derived() 
    if obj.dynamicType === Derived.self { 
     print("obj is Derived type") 
    } 
+0

貌似在新版本的swift 2.0中不支持obj.dynamicType – Feru

+0

@Feru真的嗎?那麼_that_會弄亂我的很多代碼!:( – matt

+0

我試過在操場上打電話給我一個錯誤'價值的類型'基'沒有成員'dynamicType'' – Feru

0

我可能有它並不需要創建一個實例的保存類型的解決方案。

這個想法是創建一個通用結構符合協議P與內部的typealias。然後,我們可以創建該結構的實例並將它們傳遞給一個函數,該函數接受符合P的參數,並且可以通過協議中的typealias訪問類型。

讓我們創建這樣的事情:

protocol TypeContainerP { 
    typealias type 
} 

struct TypeContainer<T>: TypeContainerP { 
    typealias type = T 
} 

現在我們可以創建TypeContainer的實例參數與一些類型:

class A {} 
class B {} 
let containerA = TypeContainer<A>() 
let containerB = TypeContainer<B>() 

,並創建函數,它TypeContainerP作爲參數,併爲我們提供了訪問通過協議鍵入:

func check<T, E: TypeContainerP>(any: T, _: E) { 
    print(any is E.type) 
} 

我們有:

check(A(), containerA) // true 
check(A(), containerB) // false 
check(B(), containerA) // false 
check(B(), containerB) // true 
1

@ matt的答案適用於Swift 2.0。在swift 3中,您可以簡單地執行以下操作:

class Base {} 
    class Derived : Base {} 

    var obj: Base = Derived() 
    let aClassType = Derived.self 

    if type(of: obj) == aClassType { 
     print("hey !") 
    } 

除非===更好。我沒有區別。