gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:02:58 28 4
gpt4 key购买 nike

我有这段代码可以创建一个 View 并对其应用渐变。

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 没有给我编译错误,但是代码在线上崩溃了

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

带有消息array element cannot be bridge to Objective-C

事实上,我原以为它会在那里崩溃,因为我不确定如何在 Swift 上创建 CGColors 数组。令人惊讶的是 Xcode 提到了 Objective-C。在我看来,我正在快速创建一个 CGColorRef ...

有什么线索吗?为什么提到 Objective-C,我该如何解决?

最佳答案

之所以提到Objective-C,是因为UIKit和QuartzCore都是Objective-C框架。特别是,gradient.colors = arrayColors正在调用一个需要 NSArray 的 Objective-C 方法.

这似乎是一个错误,因为 Apple 的文档听起来数组应该自动桥接到 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]

关于swift - 数组元素不能桥接到 Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113354/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com