Swift - 数据类型问题

时间:2015-07-16 14:02:04

标签: ios swift

我在应用程序启动时将一些数据加载到NSUserDefaults中,当用户查看相应的View时,将数据加载到TableView中。我遇到了数据类型的问题,但无论我尝试哪种方式,似乎都会出现错误。

我哪里错了。我正在跳过一些代码而只提供重要的部分。我不断收到像“无法将Bool分配给AnyObject”这样的错误

// startup function which loads the data
var categorys : [[String:Bool]] = [["All": true]]
for (index: String, category: JSON) in output {
    categorys.append([category["name"].string!: true])
}
NSUserDefaults.standardUserDefaults().setObject(categorys, forKey: "categorys")


// view controller

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var categorys: [[String:Bool]] = []

    func buildTableView() {
        if let categorys = NSUserDefaults.standardUserDefaults().arrayForKey("categorys") {
            for category in categorys {
                self.categorys.append([category["name"] as! String: category["selected"] as! Bool])
            }
            // Was trying to just assign straight away but fails
            // self.categorys = categorys
        }
    }


// then later on I want to be able to do the following
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        cell.textLabel?.text = self.categorys[indexPath.row]["name"] as? String
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if (self.categorys[indexPath.row]["selected"] as? Bool == true) {
            self.categorys[indexPath.row]["selected"] = "false"
        }
    }
}

我可能还应该提到我正在尝试使用不同的数据类型,之前我的使用更符合逻辑但也有类似的问题。

["name": [category["name"].string!, "selected": true]]

我还应该提到这是我的tableview的数据,我想更新布尔值,如果没有选择单元格。

2 个答案:

答案 0 :(得分:0)

要在Bool中使用NSUserDefaults,您必须使用setBool: forKey:

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "key")

否则会出现问题,您必须做一些变通办法,例如将Bool存储在NSNumberString中。

答案 1 :(得分:0)

你在评论中说你有一个关于“找到nil”的错误,但它与“无法将Bool分配给AnyObject”的错误实际上并不相同......

对于nil错误,您必须替换那些强制类型转换:

category["name"] as! String
带有可选绑定的

if let name = category["name"] as? String {

}

现在它会失败但如果属性为nil则不会崩溃,并且会正确附加到字典数组:

let category = ["name":"me", "selected":true]

var categorys: [[String:Bool]] = []

if let name = category["name"] as? String, let selected = category["selected"] as? Bool {
    categorys.append([name:selected])
} else {
    // oops, a value was nil, handle the error
}

与其他操作相同,请勿使用强制转换:

if let myBool = self.categorys[indexPath.row]["selected"] where myBool == true {
    self.categorys[indexPath.row]["selected"] = false
}

由于self.categorys[indexPath.row]["selected"]是Bool类型,因此不要指定类似“false”的字符串,而是指定实际的false值。