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)
let arrayColors = [cor1.CGColor,cor2.CGColor]
与消息数组元素不能桥接到Objective-C
事实上,我期待它崩溃那里,因为我不知道如何我可以创建一个CGColors在Swift数组。这里的惊喜就是Xcode提到的Objective-C。在我心中我正在创建一个CGColorRef在swift …
任何线索?为什么它提到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]