0

I'm new to Swift and I'm having a problem with UIColors in SpriteKit. I'm declaring a set of colors in an enum like this:

enum Colors {
static let red = UIColor(red: 231/255, green: 76/255, blue: 60/255, alpha: 1)
}

Then I set a SKSpriteNode, arbitrarily called element, to that colour, like:

element.color = Colors.red

If I print the values now, this will be the result:

print(Colors.red)

UIExtendedSRGBColorSpace 0.905882 0.298039 0.235294 1

print(element.color)

UIExtendedSRGBColorSpace 0.905882 0.298039 0.235294 1

And apparently they look the same, but if I do this:

print(element.color == Colors.red)

It's going to return false

Can anyone explain to me why this is happening? Thanks in advance.

Alessandro Favero
  • 205
  • 1
  • 2
  • 8
  • What is `element`? – rmaddy Jan 10 '19 at 22:54
  • Sorry about that I should have been more clear. element is a SKSpriteNode – Alessandro Favero Jan 10 '19 at 23:00
  • When you print a `UIColor`, each component is shown to 6 decimal places. But if you pull out each value and print them with more precision, they actually differ in the 7th decimal place. So it would seem that a `UIColor` value assigned to an `SKSpriteNode` actually gets modified in a small way that makes it ever so slightly different than the original. I have no idea why. – rmaddy Jan 10 '19 at 23:10
  • Look at this, alternative ways are here that can help you https://stackoverflow.com/questions/36612843/how-to-compare-a-color-in-swift – willow Jan 10 '19 at 23:16
  • Thanks, @rmaddy! – Alessandro Favero Jan 10 '19 at 23:25
  • @Ehsan But we already know the two colors are different. The question really boils down to why they are different (especially since printing them confusingly makes them appear the same). – rmaddy Jan 10 '19 at 23:28

1 Answers1

0

I think I found the reason: SKSpriteNode has a color with P3DisplayColorSpace as the default. You may play around:

  enum Colors {
    static let red = UIColor.init(displayP3Red: 231/255, green: 76/255, blue: 60/255, alpha: 1)

}




 element.color = Colors.red
 print(Colors.red)
 print(element.color)
 print (type(of:element.color))
 print (type(of:Colors.red))
 print(Colors.red == Colors.red)
 print(     element.color ==   element.color)
 print (Colors.red == element.color)
 print(     element.color.cgColor.components![0] ==   Colors.red.cgColor.components![0])
 print(     element.color.cgColor.components![0] )
 print(    Colors.red.cgColor.components![0] )
E.Coms
  • 11,065
  • 2
  • 23
  • 35