【问题标题】:How could I type check CGColor / CGPath?我如何输入检查 CGColor / CGPath?
【发布时间】:2016-07-07 18:02:46
【问题描述】:

所以看起来有一个与 CoreFoundation 类型相关的filed bug for swift。根据描述,似乎没有对 CGPath 和 CGColor 进行类型检查,下面是演示该行为的错误的 sn-p。

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

有没有人找到解决此问题的可靠解决方法?因为我不想将这个 hack 用作长期解决方案

【问题讨论】:

  • 我不熟悉这个问题,但与其与硬编码常量269 进行比较,不如与CGColorGetTypeID() 进行比较。
  • @MartinR 太棒了,这正是我想要的!我不想硬编码这个值以防它改变:)

标签: ios iphone swift core-animation core-foundation


【解决方案1】:

Apple writes:

由于类型 ID 的值可能因版本而异,因此您的代码不应依赖于存储或硬编码的类型 ID,也不应硬编码类型 ID 的任何观察到的属性(例如,它是一个小整数)。

这意味着您应该在 runtime 获取类型 ID,在您的情况下:

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

【讨论】:

    猜你喜欢
    • 2016-01-04
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多