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,我如何解决这个问题?
这似乎是一个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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。