2016-07-07 36 views
2

所以看起來有一個filed bug for swift與CoreFoundation類型有關。根據描述,看起來沒有CGPath和CGColor的類型檢查,下面是錯誤中的一個片段,它演示了這種行爲。如何輸入CGColor/CGPath?

func check(a: AnyObject) -> Bool { 
    return a is CGColor 
} 

check("hey") --> true 
check(1.0) --> true 
check(UIColor.redColor()) --> true 

這裏是我想要做的

if let value = self.valueForKeyPath(keyPath) { 
    if let currentValue = value as? CGColor { 
     // Do Something with CGColor 
    } else if let currentValue = value as? CGSize { 
     // Do Something with CGSize 
    } else if let currentValue = value as? CGPoint { 
     // Do Something with CGPoint 
    } 
} 

我已經做了以下的,按類型檢查型,我知道第一次的工作類型,然後對AnyObject最後聲明標記,並檢查CFTypeID。這現在可行,但Apple Documentation說CFTypeID可以改變,不應該依賴。

if let currentValue = value as? CGPoint { 
     // Do Something with CGPoint 
    } else if let currentValue = value as? CGSize { 
     // Do Something with CGSize 
    } else if let currentValue = value as? AnyObject { 
     if CFGetTypeID(currentValue) == 269 { 
       // Cast and do Something with CGColor 
       methodCall((currentValue as! CGColor)) 
     } 
    } 

是否有人在這個問題上找到了可靠的解決方法?因爲我不想用這個黑客是一個長期的解決方案

+1

我不熟悉這個問題,但不是針對硬編碼的常數'269對比'你可以比較'CGColorGetTypeID()'。 –

+0

@MartinR驚人的,這正是我正在尋找!我不想硬編碼該值,以防它改變:) – AntonTheDev

回答

3

Apple writes:

因爲對於一個類型ID值可以因版本改變,你的代碼不應該依賴於存儲或硬編碼類型ID也不應該硬編碼任何觀察到的類型ID屬性(例如,它是一個小整數)。

這意味着,你應該在運行獲得式ID,你的情況:

if CFGetTypeID(currentValue) == CGColorGetTypeID() { ... }