加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:04:20 所属栏目:百科 来源:网络整理
导读:我有这个代码,创建一个视图,并应用一个梯度。 import UIKitimport QuartzCorelet rect : CGRect = CGRectMake(0,320,100)var vista : UIView = UIView(frame: rect)let gradient : CAGradientLayer = CAGradientLayer()gradient.frame = vista.boundslet 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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读