Author Topic: How to use NSFastEnumeration in Swift  (Read 9398 times)


  • Administrator
  • *****
  • Posts: 719
    • View Profile
How to use NSFastEnumeration in Swift
« on: February 09, 2015, 11:42:53 AM »
There are a number of collections in Cocoa Touch that adopt the NSFastEnumeration protocol (such as NSMapTable, NSEnumerator, NSDirectoryEnumerator), allowing you to perform for-in loops on the items in the collection.

Unfortunately, Apple doesn't currently support NSFastEnumeration in Swift. If you try to use a for-in to loop through these collections you will get a compile time error:

"...does not have a member named Generator".

To get around this oversight, you can implement the SequenceType protocol in an extension. For example:

Code: [Select]
extension NSMapTable: SequenceType {
    public func generate() -> NSFastGenerator {
        return NSFastGenerator(self)

Now you can iterate through the items in the NSMapTable using a for-in loop!

Note: If you're not familiar with NSMapTable, it offers a powerful option for holding weak references to objects. If an object that is being referenced from an NSMapTable is deallocated, it is automatically removed from the collection!

All the best!
Kevin McNeish
Author of Learn to Code in Swift:
« Last Edit: August 23, 2015, 04:42:00 AM by kjmcneish »