Swift'如果让...作为?'用NSMutableArray安全解包

时间:2015-07-31 03:57:36

标签: swift nsmutablearray optional

我正在学习如何在Swift中安全地展开选项,但由于某种原因,filteredList [0]必须在这里返回nil,因为if let语句中的代码都没有执行。但是,打印filteredList可确保NSMutableArray内部存在某些内容!看起来很简单,但为什么这会回来的呢?和/或if let语句中的代码没有执行?

func filterOutNoItemsInCommon(randomItem: (NSArray) -> NSDictionary, listOfItems: NSArray) -> (NSArray, NSArray, Set<String>) {

var filteredList = NSMutableArray()
var filteredListCounter = 0
var setOfAtt: Set = Set<String>()
var selectedItem = NSArray()
var rank: Int = 0

if let itemArray: NSArray = randomItem(listOfItems)["attributes"] as? NSArray {
    selectedItem = itemArray
    for item in itemArray {
        setOfAtt.insert(item as! String)
    }
}

for number: Int in 0..<listOfItems.count {

    rank = 0

    if let listOfItems = (listOfItems[number]["attributes"] as? NSArray) {
    if let arrayOfItems = listOfItems as? Array<String> {

        if !setOfAtt.isDisjointWith(arrayOfItems) {

            filteredList.addObject(listOfItems[number])

            for ln in arrayOfItems {
                if setOfAtt.contains(ln) {
                    rank++
                }
            }

            var dictForRank: NSMutableDictionary = ["rank": rank]
            println(dictForRank)
            println("TEST\(filteredList[0])")
            // this is where the code doesn't execute
            if let thisIsAnArray = filteredList[0] as? NSMutableArray {
                println("TEST123")
                println(thisIsAnArray)
                filteredList[filteredListCounter].addObject(dictForRank)
            }

            filteredListCounter++
        }
    }
    }

}

return (filteredList, selectedItem, setOfAtt)
}

1 个答案:

答案 0 :(得分:1)

对象是NSDictionaryNSMutableDictionary,而不是NSMutableArray,因此安全保真投降失败。

你的推理是nil是不正确的; nil 不兼容的类型会导致安全展开/向下转发失败。