How do I get first x elements of an NSArray in Cocoa?

前端 未结 4 585
醉梦人生
醉梦人生 2020-12-16 09:19

New to Cocoa, and seem to be missing something.

What is the most elegant/idiomatic way to obtain the first x elements of an NSArray as another N

相关标签:
4条回答
  • 2020-12-16 09:28
    firstNItems = [items subarrayWithRange:NSMakeRange(0, MIN(n, items.count))];
    
    0 讨论(0)
  • 2020-12-16 09:30

    In Swift 3 you can use this:

    let smallArray = largeArray.prefix(10)
    
    0 讨论(0)
  • 2020-12-16 09:40

    2nd parameter is number of array items to include in the range, not the 'to' index

    0 讨论(0)
  • 2020-12-16 09:46

    You can use subarrayWithRange:.

    NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, 10)];
    
    0 讨论(0)
提交回复
热议问题