gpt4 book ai didi

swift - 带有 AnyObject 下标的 Realm.io

转载 作者:行者123 更新时间:2023-11-28 08:56:38 24 4
gpt4 key购买 nike

我即将在我的 Swift 2.0 应用程序中实现 Realm 模型。但是,一旦我安装了 Realm。我的应用程序的 AnyObject 下标会导致编译错误

Cannot subscript a value of type 'AnyObject' with an index of type 'String'

Cannot subscript a value of type 'RLMProperty' with an index of type 'String'

Conditional cast from 'RLMProperty' to 'AnyObject' always succeeds

但问题是 outlet 一开始就不应该是 RLMProperty

下面是我的代码

var campaigns = [AnyObject]()

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let campaignCell = tableView.dequeueReusableCellWithIdentifier("campaignCell", forIndexPath: indexPath) as! CampaignTableViewCell

let outlet: AnyObject = (self.campaigns[indexPath.section]["surveys"]!![indexPath.row])["outlet"]!!


// Configure the cell...
campaignCell.outletID.text = outlet["code"] as? String
campaignCell.outletNameLabel.text = outlet["name"] as? String
//campaignCell.outletAddressLabel.text = outlet["outlet"]!!["address"] as? String
campaignCell.outletStatusLabel.text = (self.campaigns[indexPath.section]["surveys"]!![indexPath.row])["progress"]!!["name"] as? String

campaignCell.outletStatusLabel.textColor = UIColor.colorWithHexString(((self.campaigns[indexPath.section]["surveys"]!![indexPath.row])["progress"]!!["color"] as? String)!)

return campaignCell
}

最佳答案

我自己遇到了这个错误 - 当您希望通过下标访问属性时,诀窍就是不要使用 AnyObject

很有可能,您的 AnyObject 实例已经是某种形式的字典。如果您知道您的键都是字符串,只需将您的对象转换为 [String: AnyObject] - 否则,使用 [NSObject: AnyObject]。您的样本中还有很多力展开,恐怕这只是在要求崩溃!那么我将如何重写您的示例?

if let campaign = self.campaigns[indexPath.section] as? [String: AnyObject],
surveys = campaign["surveys"] as? [AnyObject],
survey = surveys[indexPath.row] as? [String: AnyObject],
outlet = survey["outlet"] as? [String: AnyObject] {

// Set up your cell here

}

长话短说,if-let 是你的 friend !无检查和类型转换合二为一!

更好的是,将您的字典映射到类/结构并享受强类型的好处 - 有很多第三方 Swift 框架可以使这更容易!

关于swift - 带有 AnyObject 下标的 Realm.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899683/

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