Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over all items in NSMapTable in Swift

Tags:

ios

swift

I'm trying something like this in Swift but not working. Error is: Type () does not conform to type BooleanType

//visibleCollectionReusableHeaderViews is of type NSMapTable!

var enumerator: NSEnumerator = visibleCollectionReusableHeaderViews.objectEnumerator()
var myValue: AnyObject!

while (( myValue = enumerator.nextObject()))
{

}

What am I doing wrong? I don't think I understand how to iterate over an NSMapTable, or even just to get the first item in it.

like image 623
NullHypothesis Avatar asked Aug 25 '14 14:08

NullHypothesis


2 Answers

In Swift, this is done using conditional assignment.

let enumerator = visibleCollectionReusableHeaderViews.objectEnumerator()

while let myValue: AnyObject = enumerator.nextObject() {
    println(myValue)
}

Note the non optional type for myValue. Otherwise this loop would be infinite as myValue continued to accept nil objects.

like image 147
Mick MacCallum Avatar answered Oct 21 '22 05:10

Mick MacCallum


Or a clearer and shorter approach (Swift 3):

for key in table.keyEnumerator() {
    print(key)
}

for object in table.objectEnumerator() ?? NSEnumerator() {
    print(object)
}
like image 31
Ian Bytchek Avatar answered Oct 21 '22 04:10

Ian Bytchek