Ben Leggiero Ben Leggiero - 4 months ago 10
Swift Question

Why won't my NSColor extension see a CGColor?

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...

Answer

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,