2016-04-22 71 views
2

實際上,我想要一個協議,它將返回一個Metatype(例如:Type.Type),我可以將它傳遞給一個Class,然後當我需要時,將一個對象到那個MetaType。我要強制轉換它的原因是,它將用於tableView出隊功能,並且我想轉換爲我分配的類型。在Swift中存儲並轉換爲Metatypes

請考慮這個精簡版(下面的完整版本)。

let anyObject: AnyObject = anything() 

let aType = type.type() // aType here is A.Type 

if let newType = anyObject as? aType { 

    print(newType) 
} 

// error: 'aType' is not a type 

我很困惑,爲什麼這不是一個類型,因爲我們可以去aType.init()來初始化它?

完整的示例代碼如下(並且可以在Playground中運行)。

import UIKit 

protocol P { 

    func type() -> A.Type 
} 

class A { 

} 

class B: A { 

} 

class C: A { 

} 

struct BData: P { 

    func type() -> A.Type { 

     return B.self 
    } 
} 

struct Foo { 

    let type: P 

    init(p: P) { 

     self.type = p 
    } 

    func create() { 

     let anyObject: AnyObject = anything() 

     let typeType = type.type() 

     if let newType = anyObject as? typeType { 

      print(newType) 
     } 
    } 

    func anything() -> AnyObject { 

     return B() 
    } 
} 

let data = BData() 

let foo = Foo(p: data) 

遊樂場執行失敗:MyPlayground.playground:43:44:錯誤: 'typeType' 不是式 如果讓NEWTYPE = anyObject爲? typeType {

回答

3

Ahmm。非常好的問題。幾天前我也有同樣的3小時疼痛。最後,我發現this answer,即主要思想是:

Swift's static typing means the type of a variable must be known at compile time.

所以,你不幸編碼(或幸運:))的方式不允許的。

+0

胡:'( 爲什麼幸運的是,你會說 – chillok

+0

@cilk,好了,我還有一個爲你解答,男人:) http://stackoverflow.com/a/1517670/2463616 – pacification

+0

啊是啊,很公平。非常安全,直到我想要變得不安全。您是否接近備用解決方案? – chillok