Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Equivalent of removeObjectsInRange:

Having a little trouble tracking down the Swift equivalent of:

//timeArray and locationArray are NSMutableArrays
NSRange removalRange = NSMakeRange(0, i);

[timeArray removeObjectsInRange:removalRange];
[locationArray removeObjectsInRange:removalRange];

I see that Swift does have a call in the API: typealias NSRange = _NSRange but I haven't got past that part. Any help?

like image 644
Jeef Avatar asked Sep 18 '14 13:09

Jeef


2 Answers

In addition to Antonio's answer, you can also just use the range operator:

var array = [0, 1, 2, 3, 4, 5]
array.removeRange(1..<3)
// array is now [0, 3, 4, 5]
  • The half-closed range operator (1..<3) includes 1, up to but not including 3 (so 1-2).
  • A full range operator (1...3) includes 3 (so 1-3).
like image 93
Aaron Brager Avatar answered Nov 08 '22 09:11

Aaron Brager


Use the removeRange method of the swift arrays, which requires an instance of the Range struct to define the range:

var array = [1, 2, 3, 4]

let range = Range(start: 0, end: 1)
array.removeRange(range)

This code removes all array elements from index 0 (inclusive) up to index 1 (not inclusive)

Swift 3

As suggested by @bitsand, the above code is deprecated. It can be replaced with:

let range = 0..<1
array.removeSubrange(range)

or, more concisely:

array.removeSubrange(0..<1)
like image 40
Antonio Avatar answered Nov 08 '22 07:11

Antonio