Array element cannot be bridged to Objective-C

The reason Objective-C is mentioned is because UIKit and QuartzCore are Objective-C frameworks. In particular, gradient.colors = arrayColors is calling an Objective-C method that expects an NSArray.

This seems like a bug, as Apple’s documentation makes it sound like that the array should auto-bridge to an NSArray so long as the items in the array can be considered AnyObject:

When you bridge from a Swift array to an NSArray object, the elements
in the Swift array must be AnyObject compatible. For example, a Swift
array of type Int[] contains Int structure elements. The Int type is
not an instance of a class, but because the Int type bridges to the
NSNumber class, the Int type is AnyObject compatible. Therefore, you
can bridge a Swift array of type Int[] to an NSArray object. If an
element in a Swift array is not AnyObject compatible, a runtime error
occurs when you bridge to an NSArray object.

You can also create an NSArray object directly from a Swift array literal, following the same bridging rules outlined above. When you
explicitly type a constant or variable as an NSArray object and assign
it an array literal, Swift creates an NSArray object instead of a
Swift array.

For now, a work around would be either to declare arrayColors as an NSArray:

let arrayColors: NSArray = [cor1.CGColor, cor2.CGColor]

Or to declare it as taking AnyObject:

let arrayColors: Array <AnyObject> = [cor1.CGColor, cor2.CGColor]

Leave a Comment