1、OC写法
@brief OC中的enumerateObjectsUsingBlock
Objective-C 中最方便的方式是使用 NSArray 的 enumerateObjectsUsingBlock: 方法。因为通过这个方法可以显式地同时得到元素和下标索引,这会有最好的可读性,并且 block 也意味着可以方便地在不同的类之间传递和复用这些代码。
- (void)test1 {
NSArray *characters = @[@"a", @"b", @"c", @"d", @"e"];
[characters enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (idx == 2) {
NSLog(@"current character is : %@", obj);
*stop = YES;
}
NSLog(@"other character is : %@", obj);
}];
}
2、swift写法1,必须将数据声明为NSArray(OC类型的数组)
数组使用enumerateObjectsUsingBlock
Swift 中,这个 API 的 *stop 被转换为了对应的 UnsafeMutablePointer<ObjCBool>。
Unsafe 开头的这些指针类型, ObjCBool的指针指向的内存的内容(memory)设置为true即可
private func test2() {
let characters: NSArray = ["a", "b", "c", "d", "e"]
characters.enumerateObjectsUsingBlock { (character, idx, stop) -> Void in
if idx == 2 {
stop.memory = true
print("current character is : \(character)")
}
print("other character is : \(character)")
}
}
3、swift写法2,swift类型的数组(Array)
EnumerateGenerator,只支持iOS9.0以后
private func test1() {
let characters = ["a", "b", "c", "d", "e"]
for (idx, character) in characters.enumerate() {
if idx == 2 {
print("current character is : \(character)")
break
}
print("other character is : \(character)")
}
}