将NSIndexPath作为键和NSNumber添加为Dictionary中的值的问题?

时间:2016-11-30 12:25:50

标签: swift dictionary boolean nsnumber nsindexpath

quickFilterDictionaryself.preferencesListFilterDictionary的第二个对象是nil。如何在NSIndexPath中添加[NSNumber]索引路径(作为键)和Dictionary(作为值)?

注意:第一个对象成功添加,当我在控制台中打印nil时,只有第二个对象为self.preferencesListFilterDictionary。我可以知道,我在下面的代码中做错了什么?

self.preferencesListFilterDictionary["price"] = 1000
self.quickFilterArr = [localizedStrOf("deliveryNowOnly"),localizedStrOf("rated")]
var quickFilterDictionary = Dictionary<NSIndexPath, NSNumber?>()
        for obj in self.quickFilterArr {
            let row = self.quickFilterArr.indexOf(obj)
            let indexPath = NSIndexPath(forRow:row!, inSection: 0)
            quickFilterDictionary[indexPath] = NSNumber(bool: false)
        }
        print(quickFilterArr.count)
        print(quickFilterDictionary)
self.preferencesListFilterDictionary.updateValue(quickFilterDictionary as? AnyObject, forKey: "quickFilterDictionaryKey")
print(self.preferencesListFilterDictionary)

控制台打印:

▿ [1] : 2 elements
    - .0 : "quickFilterDictionaryKey"
    - .1 : nil

为了从数字上面获取字典bool,我写了下面的代码 -

func getQuickFilterValueOfIndexpath(indexPath:NSIndexPath) -> Bool {
        if let val = self.preferencesListFilterDictionary["quickFilterDictionaryKey"] {
            // now val is not nil and the Optional has been unwrapped, so use it
            let tempDict = val as! Dictionary<NSIndexPath, NSNumber?>
            if let boolVal = tempDict[indexPath] {
                return boolVal!
            }
        }

        return false
    }

1 个答案:

答案 0 :(得分:0)

我认为你对Row,IndexPath和Index之间的区别感到困惑。

在以下代码中:

let row = self.quickFilterArr.indexOf(obj)

如果您选择单击行,您将看到它是Array.Index?类型的对象。这不是一排。

还有一个原因是你使用NSNumber,NSIndexPath和更新密钥值?与Number,IndexPath相反,只需使用以下内容更新字典值:    preferencesListFilterDictionary [“quickFilterDictionaryKey] = quickFilterDictionary

如果您选择单击quickFilterArr并且它是一个IndexPaths数组[IndexPath] - 要在您所选择的索引中引用IndexPath,您可以这样做:

if let arrayIndex = quickFilterArr.indexOf(obj) {
//if your array is an array of Index Paths
//you would then pull the IndexPath object at the index you have defined above
  let indexPath = quickFilterArr[arrayIndex]
  quickFilterDictionary[indexPath] = Number(bool: false)
}