If you try and add a gradient background in Swift to a View you will more than likely get this error: fatal error: array element cannot be bridged to Objective-C
I hit this problem trying to add a gradient background. My initial implementation of a gradient background looked like this:
How to successfully add a gradient background in Swift
Extensions add new functionality to an existing class, structure of enumeration type. I opted to extend CAGradientLayer with a new function turquoiseColor() allowing me to get a new torquiseColor gradient directly from the CAGradientLayer class. The code below shows how to display the gradient as a background for a view.
This code should of worked, unfortunately it didn’t :-[. When I ran the application I got the error: “fatal error: array element cannot be bridged to Objective-C”. The stackoverflow post provided the solution; gradient.colors = arrayColors calls an Objective-C method thats expects an NSArray.
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.
Declaring the array as Array <AnyObject> overcomes this issue though:
Your gradient will now be successfully displayed. As you need more gradients of different colors, these colors can bee added to the the CAGradientLayer extension.