I need a Swift dictionary that can store any kind of object. Some of the values will be CGColor
references. I have no issue creating the dictionary and storing the CGColor
references. The problem is trying to safely get them back.
let color = CGColor(gray: 0.5, alpha: 1)
var things = [String:Any]()
things["color"] = color
things["date"] = Date()
print(things)
That works and I get reasonable output. Later on I wish to get the color (which may or may not exist in the dictionary. So naturally I try the following:
if let color = things["color"] as? CGColor {
print(color)
}
But this results in the error:
error: conditional downcast to CoreFoundation type 'CGColor' will always succeed
In the end I came up with:
if let val = things["color"] {
if val is CGColor {
let color = val as! CGColor
print(color)
}
}
This works without any warnings in a playground but in my actual Xcode project I get a warning on the if val is CGColor
line:
'is' test always true because 'CGColor' is a Core Foundation type
Is there good solution to this problem?
I'm working with core graphics and layers and the code needs to work with both iOS and macOS so I'm trying to avoid UIColor
and NSColor
.
I did find Casting from AnyObject to CGColor? without errors or warnings which is related but doesn't seem relevant any more since I don't need the parentheses to eliminate the warning plus I'm trying to use optional binding which isn't covered by that question.