我需要获得最后10个元素或10分钟和array.count。在Objective-C中,我这样做了:
Objective-C代码:
NSRange endRange = NSMakeRange(sortedArray.count >= 10 ? sortedArray.count - 10 : 0, MIN(sortedArray.count, 10));
NSArray *lastElements= [sortedArray subarrayWithRange:endRange];
在Swift中我做到了:
let endRange = NSMakeRange(values.count >= 10 ? values.count - 10 : 0, min(values.count , 10) )
但是不知道如何在swift中使用这个范围来获取数组。任何帮助,将不胜感激。感谢。
答案 0 :(得分:11)
您可以使用数组实例方法suffix(_:)
。请注意,使用后缀不需要检查数组计数。从数组末尾开始最多需要10个元素。
let array = Array(1...100) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
let lastTenElements = Array(array.suffix(10)) // [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
答案 1 :(得分:1)
您可以通过声明Range:
来获取它let letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]
let desiredRange = letters.index(letters.endIndex, offsetBy: -10) ..< letters.endIndex
// ["e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]
let lastTenLetters = (desiredRange.count > letters.count) ? letters : Array(letters[desiredRange])
请注意,如果所需范围的计数大于主数组的计数,则最后十个元素应该是整个主数组。
虽然我仍然同意Leo's answer适合您的情况,但我想提一下,这个解决方案的好处在于它不仅适用于最后一个元素,而且要清楚,考虑你希望在第一个元素之后获得10个元素(引用letters
数组,元素应该是 bk ),通过实现所需的范围,你可以实现这一点,如下所示:
let letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]
let desiredRange = letters.index(letters.startIndex, offsetBy: 1) ..< letters.index(letters.startIndex, offsetBy: 11)
// ["b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
let lastTenLetters = (desiredRange.count > letters.count) ? letters : Array(letters[desiredRange])
答案 2 :(得分:0)
var值:NSArray = [1,2,3,4,5,6,7,8,9,10,11]
values = values.reversed() as NSArray
let tenDigits = values.prefix(10)
debugPrint(values.count >= 10 ? NSArray(array: (Array(tenDigits))) : min(values.count , 10))