Reputation: 471
I'm learning how to safely unwrap optionals in Swift, for some reason however filteredList[0] must be returning nil here, as none of the code inside the if let statement is executing. However, printing the filteredList ensures that there is something inside that NSMutableArray! It seems pretty simple, but why is this returning nil? and/or the code inside the if let statement not executing?
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)
}
Upvotes: 0
Views: 545
Reputation: 8718
The object is an NSDictionary
or NSMutableDictionary
, not an NSMutableArray
, so the safe downcast is failing.
Your reasoning that it is nil
is incorrect; either nil
or an incompatible type will cause a safe unwrap/downcast to fail.
Upvotes: 1