2014-09-23 46 views
2

我定義了兩種類型,如下所示:我想定義一個函數'matches'來比較兩個KeyTypePairs並返回true或false取決於key和type的匹配。swift - 我可以比較Any.Type嗎?

protocol KeyTypePair: Hashable { 
    typealias val 

    var key: String { get } 
    var type: Any.Type { get } 
} 

public struct KeyTypePairOf<T>: KeyTypePair { 
    typealias val = T 

    let _key: String 
    let _type: Any.Type 

    public var key: String { 
     get { 
      return _key 
     } 
    } 

    public var type: Any.Type { 
     get { 
      return _type 
     } 
    } 

    public var hashValue: Int { 
     get { 
      return _key.hashValue 
     } 
    } 

    public init(key: String) { 
     self._key = key 
     self._type = T.self 
    } 

    init<T: KeyTypePair>(property: T) { 
     self._key = pair.key 
     self._type = pair.type 
    } 

    func matches<T: KeyTypePair>(pair:T) -> Bool { 
     let x = self._type == pair.type // invalid, how do I check equal types? 
     return self._key == pair.key && x 
    } 

} 

如何比較結構的「類型」?頭痛。我應該使用AnyObject嗎?

回答

2

你想要的工具是object_getClassName(它返回String)。現在,你不能直接比較類型。這感覺就像是一個缺少的編譯器功能,而不是任何關於swift的深入。你會認爲你可以比較x.dynamicType == y.dynamicType,但目前沒有工作。另請參見What is the pattern for entities and Equatable?

+1

只能使用'object_getClassName'的對象。如果它們都是對象,那麼可以使用'x.dynamicType作爲AnyObject === y.dynamicType作爲AnyObject' – newacct 2014-09-24 08:37:29

0

我測試了在斯威夫特4操場

struct Foo {} 
struct Bar {} 

let fooType: Any.Type = Foo.self 
let barType: Any.Type = Bar.self 

fooType == Foo.self // true 
fooType is Foo.Type // true 
fooType == barType // false 
相關問題