ios - 无法将类型 'NSObject?' 的值分配给类型 'UIColor?' 的值

标签 ios swift dictionary uicolor

我试图将单元格的背景颜色设置为等于字典中的 UI 颜色,但我不断收到以下错误。即使将其作为数组传递时它也能工作吗?

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    let colourList = [["Color" : "Red", "colourCode" : UIColor.redColor()],
                        ["Color" : "Yellow", "colourCode" :     UIColor.yellowColor()],
                        ["Color" : "Purple", "colourCode" : UIColor.purpleColor()],
                        ["Color" : "Green", "colourCode" : UIColor.greenColor()],
                        ["Color" : "Blue", "colourCode" : UIColor.blueColor()],
                        ["Color" : "Orange", "colourCode" : UIColor.orangeColor()]]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.dataSource = self
        self.tableView.delegate = self
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let dict = colourList[indexPath.row]
        print(dict) // e.g ["Colour": "Red", "colourCode": UIDeviceRGBColorSpace 1 0 0 1] 
        print(dict["colourCode"]!) // e.g UIDeviceRGBColorSpace 1 0 0 1
        cell.backgroundColor = dict["colourCode"] \\ ERROR - Cannot assign a value of type 'NSObject?' to a value of type 'UIColor?'

        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.colourList.count
    }
}

最佳答案

用作!明确告诉它的类型

cell.backgroundColor = dict["colourCode"] as! UIColor

关于ios - 无法将类型 'NSObject?' 的值分配给类型 'UIColor?' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32295491/

相关文章:

ios - 什么会导致 NSUserDefaults 被清除

ios - 在 "as!"之后发送类类型作为参数

java - 这是在 Java 中使用实例变量的正确方法吗?

python - 在 python 中对字典进行排序并将结果作为字典返回

ios - dequeueReusableCellWithReuseIdentifier : and cellForItemAtIndexPath: 之间的区别

iphone - 在将应用程序提交到 App Store 之前忘记删除断点

objective-c - 判断之前是否安装过app

swift - 我下载了一个使用 CocoaPods 的开源项目。我必须安装 CocoaPods 吗?

ios - 显示键盘时Swift ios移动文本字段

javascript - jQuery - 将元素列表更改为关联数组