Casting from AnyObject to CGColor? without errors or warnings

◇◆丶佛笑我妖孽 提交于 2019-12-08 19:34:17

问题


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


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!