如何输入检查CGColor/CGPath? [英] How could I type check CGColor / CGPath?

查看:64
本文介绍了如何输入检查CGColor/CGPath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以看来,有一个与CoreFoundation类型有关的提起的Swift漏洞.根据描述,似乎没有针对CGPath和CGColor的类型检查,下面是该错误的片段,演示了该行为.

So what it appears there is a filed bug for swift relating to the CoreFoundation types. Based on the description it appears there is not type checking for CGPath and CGColor, below is a snippet from the bug that demonstrates the behavior.

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文档说CFTypeID可以更改,因此不应依赖.

I've done the following, by type checking type the types I know work first, then tagging on the last statement for AnyObject, and checking the CFTypeID. This works for now, but Apple Documentation says that the the CFTypeID can change, and should not be relied upon.

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

有人找到了解决此问题的可靠方法吗?因为我不想将此黑客作为长期解决方案

Has anyone found a reliable workaround a for this issue? As I do not want to use this hack as a long term solution

推荐答案

由于类型ID的值可以在各个发行版之间变化,因此您的代码不应依赖于已存储或硬编码的类型ID,也不应对任何已观察到的类型ID的属性进行硬编码(例如,它是一个小整数).

Because the value for a type ID can change from release to release, your code should not rely on stored or hard-coded type IDs nor should it hard-code any observed properties of a type ID (such as, for example, it being a small integer).

这意味着您应在 runtime 上获取类型ID,具体情况如下:

That means that you should obtain the type ID at runtime, in your case:

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

这篇关于如何输入检查CGColor/CGPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆