ioscastingcompiler-warningscgcoloranyobject

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


Solution

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