如何使用Swift遍历NSMapTable中的所有项目

时间:2022-03-08 19:28:31

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

我正在用Swift尝试类似的东西,但没有效果。错误是: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.

我做错了什么?我不知道如何遍历一个NSMapTable,甚至不知道如何获取其中的第一个条目。

3 个解决方案

#1


11  

In Swift, this is done using conditional assignment.

在Swift中,这是使用条件赋值完成的。

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.

注意myValue的非可选类型。否则这个循环将是无限的,因为myValue继续接受nil对象。

#2


0  

Or a clearer and shorter approach (Swift 3):

或更清晰更短的方法(Swift 3):

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

for object in table.objectEnumerator() ?? NSEnumerator() {
    print(object)
}

#3


-1  

In Swift 3 you can use for-in loop through allObjects property:

在Swift 3中,可以通过allObjects属性使用forin循环:

for myValue in visibleCollectionReusableHeaderViews.allObjects {
  // do stuff
} 

#1


11  

In Swift, this is done using conditional assignment.

在Swift中,这是使用条件赋值完成的。

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.

注意myValue的非可选类型。否则这个循环将是无限的,因为myValue继续接受nil对象。

#2


0  

Or a clearer and shorter approach (Swift 3):

或更清晰更短的方法(Swift 3):

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

for object in table.objectEnumerator() ?? NSEnumerator() {
    print(object)
}

#3


-1  

In Swift 3 you can use for-in loop through allObjects property:

在Swift 3中,可以通过allObjects属性使用forin循环:

for myValue in visibleCollectionReusableHeaderViews.allObjects {
  // do stuff
}