Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting from AnyObject to CGColor? without errors or warnings

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 = borderColorBoth 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

like image 836
Jacob R Avatar asked Nov 07 '15 23:11

Jacob R


2 Answers

You are using layer color, which is core graphics, you need to set core graphic color with property cgColor

layer.borderColor = UIColor.red.cgColor
like image 70
Shuja Ud Din Avatar answered Oct 10 '22 20:10

Shuja Ud Din


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.

like image 25
abanet Avatar answered Oct 10 '22 19:10

abanet