Casting from AnyObject to CGColor? without errors or warnings
Asked Answered
M

3

12

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

Mirisola answered 7/11, 2015 at 23:52 Comment(0)
C
5

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)
Crabwise answered 7/11, 2015 at 23:57 Comment(2)
This just makes the warning go away, it doesn't resolve the underlying problem. I'm myself looking for the correct answer so I don't know what it is, but I don't think that it's that.Nic
This seems to have the correct answer: #43927667Nic
M
8

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

layer.borderColor = UIColor.red.cgColor
Mesognathous answered 27/9, 2017 at 14:43 Comment(1)
Good use of the UIColor cgColor property! Didn't even know this existed and Xcode didn't help me find it.Presentday
C
5

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)
Crabwise answered 7/11, 2015 at 23:57 Comment(2)
This just makes the warning go away, it doesn't resolve the underlying problem. I'm myself looking for the correct answer so I don't know what it is, but I don't think that it's that.Nic
This seems to have the correct answer: #43927667Nic
G
2

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.

Gudrun answered 9/10, 2018 at 15:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.