Swift 2.2 enumerateObjectsUsingBlock - 停止

时间:2016-03-29 21:41:58

标签: ios swift

在Swift 2.2之前,我可以通过使用var对stop参数进行可变,然后适当地设置它来停止枚举stop = UnsafeMutablePointer<ObjCBool>.alloc(NSNumber(bool: true).integerValue)

现在在2.2中,不建议使用参数mutable,那么如何停止枚举?

2 个答案:

答案 0 :(得分:4)

你的语法很奇怪; - )

这适用于Swift 2.1和2.2

let array: NSArray = [1, 2, 3, 4, 5]
array.enumerateObjectsUsingBlock { (object, idx, stop) in
  print(idx)
  if idx == 3 {
    stop.memory = true
  }
}

斯威夫特3:

let array: NSArray = [1, 2, 3, 4, 5]
array.enumerateObjects({ (object, idx, stop) in
    print(idx)
    if idx == 3 {
        stop.pointee = true
    }
})

尽管如此 - 正如其他答案所示 - 使用原生Swift Array

答案 1 :(得分:0)

您应该使用Swift提供的工具:

for (idx, value) in array.enumerate(){
    print(idx)
    if idx == 10 { break }
}

正如您在评论中澄清的那样,您正在枚举PHFetchResult,请使用以下扩展来启用swift枚举:

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)")
}

结果:

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 
相关问题