swift – 数组元素不能桥接到Objective-C

前端之家收集整理的这篇文章主要介绍了swift – 数组元素不能桥接到Objective-C前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个代码,创建一个视图,并应用一个梯度。
import UIKit
import QuartzCore


let rect : CGRect = CGRectMake(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给我没有编译错误,但代码是崩溃的行

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

与消息数组元素不能桥接到Objective-C

事实上,我期待它崩溃那里,因为我不知道如何我可以创建一个CGColors在Swift数组。这里的惊喜就是Xcode提到的Objective-C。在我心中我正在创建一个CGColorRef在swift …

任何线索?为什么它提到Objective-C,我如何解决这个问题?

提到Objective-C的原因是因为UIKit和QuartzCore是Objective-C框架。特别是,gradient.colors = arrayColors调用一个期望NSArray的Objective-C方法

这似乎是一个bug,因为苹果的文档使它听起来像数组应该自动桥接到一个NSArray,只要数组中的项可以被认为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.

现在,一个解决方法是将arrayColors声明为NSArray:

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

或者声明为接受AnyObject:

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

原文链接:https://www.f2er.com/swift/321042.html

猜你在找的Swift相关文章