Search code examples
swiftswift3type-conversionambiguousnscolor

NSColor.init?(cgColor: aCGColor) ambiguous reference


I want to get an NSColor from an existing CGColor with the func
NSColor.init?(cgColor: aCGColor) according to the docs

var linienfarbe = CGColor.init(red:0.0,green: 0.0, blue: 1.0,alpha:1.0)
let textfarbe:NSColor = NSColor.init?(cgColor:linienfarbe)

I am getting the error:

Ambiguous reference to member 'init(colorLiteralRed:green:blue:alpha:)

What is going wrong?


Solution

  • Get rid of the optional bit after init:

    var linienfarbe = CGColor.init(red:0.0,green: 0.0, blue: 1.0,alpha:1.0)
    let textfarbe:NSColor? = NSColor.init(cgColor:linienfarbe)
    

    The above result will be an optional.

    or you can do:

    let textfarbe:NSColor = NSColor.init(cgColor:linienfarbe)!
    

    Also, if you're not going to change linienfarbe again, make it an immutable let.