【问题标题】:Issues adding NSIndexPath as key and NSNumber as value in Dictionary?在字典中添加 NSIndexPath 作为键和 NSNumber 作为值的问题?
【发布时间】:2016-11-30 12:25:49
【问题描述】:

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

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

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

为了从数字中获取字典布尔值,我编写了以下代码 -

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
    }

【问题讨论】:

    标签: swift dictionary boolean nsnumber nsindexpath


    【解决方案1】:

    我认为您对 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)
    }
    

    【讨论】:

    • 嗨@Kayla Galway,你错过了这个声明 - self.quickFilterArr = [localizedStrOf("deliveryNowOnly"),localizedStrOf("rated")]
    猜你喜欢
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2018-04-22
    相关资源
    最近更新 更多