Nsfastenumeration in Swift

NSFastEnumeration in Swift

After a while poking around the swift framework files, I finally found this nice class called NSFastGenerator. NSSet and friends seem to be using the same Generator.

For ZBarSymbolSet, here's how you'd extend it to support for-in loops:

extension ZBarSymbolSet: SequenceType {
public func generate() -> NSFastGenerator {
return NSFastGenerator(self)
}
}

Update: Looks like Swift 2.0's protocol extensions fixed this for us!

NSFastEnumeration in Swift 3

In Swift 3, SequenceType has been renamed to Sequence (the "Type" suffix has been removed from protocols), generate() has been renamed to makeIterator() (the concept of a "Generator" has been replaced by an "Iterator") and therefore NSFastGenerator has also been renamed to NSFastEnumerationIterator.

Thus you'll want your extension to look like this:

extension CMSensorDataList : Sequence {
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}

PHAssetCollectionChangeRequest: addAssets() now accepts NSFastEnumeration. how to achieve this?

So, I did some research, and according to NSHipster, NSEnumeration is a protocol implemented by NSArray, NSSet, and NSDictionary. This suggests that if you convert [assetPlaceholder] to an NSArray, you'll be able to use it in the method. And, in fact, this compiles:

let enumeration: NSArray = [assetPlaceholder!]
albumChangeRequest!.addAssets(enumeration)

support for-each in custom class swift

The answer for calling from objective-c with for-each to swift class,
is by changing the Array to NSArray and implement NSFastEnumeration.

@objcMembers public class FeedItemsCollection:NSObject,NSFastEnumeration,Sequence
{
//private var feedItems:[FeedItem]
private var feedItems:NSMutableArray

public init(feedItems :NSMutableArray)
{
self.feedItems = feedItems
}
public func makeIterator() ->NSFastEnumerationIterator
{
return NSFastEnumerationIterator(self)
}
public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int {

return self.feedItems.countByEnumerating(with: state, objects: buffer, count: len);
}

}

and the objective-c code that call for-each loop

   self.feedItemsCollection = [[FeedItemsCollection alloc] initWithFeedItems:entities];

for(FeedItem * feedItem in self.feedItemsCollection)
{
NSLog(@"feedItem-title = %@", feedItem.title);
}

NSFastEnumerationIteration.member Swift 3

In Swift 3 you need to specify the type of object,so specify the type of your data Array to [[String:Any]].

if let dataArr = data as? [[String: Any]] {
for dd in dataArr {
//your code for accessing dd.
}
}


Related Topics



Leave a reply



Submit