Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

swift - Array element cannot be bridged to Objective-C

I have this code that creates a view and applies a gradient to it.

import UIKit
import QuartzCore


let rect : CGRect = CGRectMake(0,0,320,100)

var vista : UIView = UIView(frame: rect)

let gradient : CAGradientLayer = CAGradientLayer()
gradient.frame = vista.bounds

let cor1 = UIColor.blackColor()
let cor2 = UIColor.whiteColor()

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

gradient.colors = arrayColors

view.layer.insertSublayer(gradient, atIndex:0)

Xcode is giving me no compile error, but the code is crashing on the line

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

with the message array element cannot be bridged to Objective-C

In fact I was expecting it to crash there, because I am not sure how I can create an array of CGColors on Swift. The surprise here is Xcode mentioning Objective-C. In my mind I was creating a CGColorRef in swift...

Any clues? Why is it mentioning Objective-C and how do I solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...