我想打印一个播放列表。以下是我将如何在python中执行此操作:
playlist = ['Classical Song', 'Rock Song', 'New Song']
for num, item in enumerate(playlist):
print '%s) %s' % (num+1, item)
1) Classical Song
2) Rock Song
3) New Song
我如何在Objective-C中做同样的事情?以下是我到目前为止的情况:
NSArray *playlist = @[@"Classical Song", @"Rock Song", @"New Song"];
for (NSString *item in playlist) {
NSLog(@"?) %@", item);
}
2014-08-23 15:56:34.421 Music[16332:303] ?) Classical Song
2014-08-23 15:56:34.423 Music[16332:303] ?) Rock Song
2014-08-23 15:56:34.423 Music[16332:303] ?) New Song
如何更改上面的内容以获取枚举循环中的数字?
答案 0 :(得分:4)
for循环中没有提供索引,但是有一个方法enumerateObjectsUsingBlock:就是这样。
NSArray *playlist = @[@"Classical Song", @"Rock Song", @"New Song"];
[playlist enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%ld) %@", idx+1, obj);
}];