Reputation: 1370
Prior to Swift 2.2 I could stop an enumeration by making the stop parameter mutable with var and then setting it appropriatelystop = UnsafeMutablePointer<ObjCBool>.alloc(NSNumber(bool: true).integerValue)
Now in 2.2 making a parameter mutable is deprecated so how do I stop an enumeration?
Upvotes: 2
Views: 1721
Reputation: 285072
Your syntax is pretty weird ;-)
This works in both Swift 2.1 and 2.2
let array: NSArray = [1, 2, 3, 4, 5]
array.enumerateObjectsUsingBlock { (object, idx, stop) in
print(idx)
if idx == 3 {
stop.memory = true
}
}
Swift 3:
let array: NSArray = [1, 2, 3, 4, 5]
array.enumerateObjects({ (object, idx, stop) in
print(idx)
if idx == 3 {
stop.pointee = true
}
})
Nevertheless – as suggested in the other answer – use native Swift Array
.
Upvotes: 5
Reputation: 52227
You should uses the tools Swift offers instead:
for (idx, value) in array.enumerate(){
print(idx)
if idx == 10 { break }
}
As you clarified in your comment, that you are enumerating a PHFetchResult, use following extensions to enable swift enumeration:
extension PHFetchResult: SequenceType {
public func generate() -> NSFastGenerator {
return NSFastGenerator(self)
}
}
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let allPhotos = PHAsset.fetchAssetsWithOptions(fetchOptions)
for (idx, photoAsset) in allPhotos.enumerate() {
if idx == 2 { break }
print("\(idx) \(photoAsset)")
}
Results in:
0 <PHAsset: 0x7fa0d9f29c40> B84E8479-475C-4727-A4A4-B77AA9980897/L0/001 mediaType=1/0, sourceType=1, (4288x2848), creationDate=2009-10-09 21:09:20 +0000, location=0, hidden=0, favorite=0
1 <PHAsset: 0x7fa0d9f29df0> 106E99A1-4F6A-45A2-B320-B0AD4A8E8473/L0/001 mediaType=1/0, sourceType=1, (4288x2848), creationDate=2011-03-13 00:17:25 +0000, location=1, hidden=0, favorite=0
Upvotes: 0