3

This baffles me... I'm trying to create a convenience initializer for NSColor which makes one out of a CGColor, but for some dang reason it just refuses to acknowledge that CGColor exists! I have imported Cocoa, and just for sanity I also imported CoreGraphics and even CoreGraphics.CGColor but still no luck!

All the imports I should need, but CGColor is not found

Can anyone tell me what I'm doing wrong? Cleaning and rebuilding doesn't help...

Ky -
  • 30,724
  • 51
  • 192
  • 308
  • 4
    Why? `NSColor` already has an [`init(cgColor:)`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSColor_Class/#//apple_ref/occ/clm/NSColor/colorWithCGColor:) – Hamish Aug 04 '16 at 13:37
  • @Hamish aw, dang... that wasn't showing up in my autocomplete for some reason. :/ – Ky - Aug 04 '16 at 13:41

2 Answers2

4

As already said in the comments, NSColor has an init(cgColor:) initializer, that might render your problem obsolete.

But since you are asking why it does not compile: The reason is that NSColor has a CGColor property, and that conflicts with the CGColor type. As a workaround, one can use the CGColorRef alias:

extension NSColor {

    convenience init(_ cgColor: CGColorRef) {
        // ...
    }
}

As Eric Aya said, the problem does not exist with Xcode 8 beta 4. The reason is that the NSColor property was renamed to cgColor, and does not conflict with the CGColor type anymore,

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2

Xcode is clearly misbehaving here. Workaround: use the complete type in the signature.

convenience init(_ cgColor: CoreGraphics.CGColor)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • 1
    Thanks for the swift answer! – Ky - Aug 04 '16 at 13:53
  • I think this solution is better than @MartinR's because it doesn't rely on the availability of a typealias, and thus is more general – Alexander Aug 04 '16 at 14:05
  • @AlexanderMomchliov: I do not disagree, but the main point of my answer was to explain *why* the problem occurs. It is not a "misbehaving compiler" but conflicting definitions in the frameworks. – Martin R Aug 04 '16 at 14:18
  • 2
    @MartinR To clarify, I like your answer more, because you give that backgorund explaination. However, I think EricAya's *solution* is better. – Alexander Aug 04 '16 at 14:24