问题
Hello StackOverflow :)
I've been running into a weird problem since I upgraded to swift 2.0
I'm trying to set a border color, so I'm writing self.layer.borderColor = borderColor as! CGColor
where borderColor is an AnyObject
, while self.layer.borderColor is a CGColor?
If I write self.layer.borderColor = borderColor as! CGColor
I get the warning
Treating a forced downcast to 'CGColor' as optional will never produce 'nil'
and is recommended to instead use as?
If I instead write self.layer.borderColor = borderColor as? CGColor
I get the error
Conditional downcast to CoreFoundation type 'CGColor' will always succeed
Just to make sure I wasn't missing something I also tried writing container.layer.borderColor = borderColor as CGColor
and container.layer.borderColor = borderColor
Both of these gave the following error:
'AnyObject' is not convertible to 'CGColor'; did you mean to use 'as!' to force downcast?
Just running with the warning given by XCode when using as!
is not all that terrible, but I would prefer to keep my code warning free. To avhieve that I really need your help SO. Is this something I'm not understanding or is it simply a bug in Swift 2.0 that I should instead report.
Cheers!
Jacob
回答1:
xcode also gives me the following hint:
Add parentheses around the cast to silence this warning
well... when xcode says so...
layer.borderColor = (borderColor as! CGColor)
回答2:
You are using layer color, which is core graphics, you need to set core graphic color with property cgColor
layer.borderColor = UIColor.red.cgColor
回答3:
Yes, it is a well-know bug and it is still unresolved! Unnecessary message for non-optional to non-optional cast
If you don't like the warning you should follow the Xcode advice:
Add parentheses around the cast to silence this warning.
来源:https://stackoverflow.com/questions/33589203/casting-from-anyobject-to-cgcolor-without-errors-or-warnings