上下文类型 CGfloat 不能与数组文本一起使用



我正在使用UIImage+Gradient.swift文件将梯度添加到我的标签中,但是我收到此错误:

上下文类型 CGFLOAT 不能与数组文本一起使用

我已经查看了一些FAQ问答,但我仍然感到困惑。

这是代码:

let components = colors.reduce([]) { (currentResult: [CGFloat], currentColor: UIColor) -> [CGFloat] in
        var result = currentResult
        let numberOfComponents = currentColor.cgColor.numberOfComponents
        let components = currentColor.cgColor.components
        if numberOfComponents == 2 {
            result.append([components?[0], components?[0], components?[0], components?[1]])
        } else {
            result.append([components?[0], components?[1], components?[2], components?[3]])
        }
        return result
    }

给出错误的行如下:

result.append([components?[0],组件?[0],组件?[0],组件?[1]]) result.append([components?[0],组件?[1],组件?[2],组件?[3]])

此错误与尝试将不是数组的变量设置为数组有关。例如,这将产生类似的错误:

var myFavSnacks:String = ["Apples","Grasses","Carrots"] //gives similar error

在您的情况下,它认为您想将 CGFloats 数组添加到数组中的一个索引中,而不是向数组中添加多个 CGFloat。

要一次将多个项目添加到数组中,请使用如下contentsOf:

colors.append(contentsOf: ["red", "blue"]) 
//adds strings "red" and "blue" to an existing array of strings called colors

从此处提供的文档:https://developer.apple.com/reference/swift/array

最新更新