Jeef
Jeef

Reputation: 27275

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?

Upvotes: 14

Views: 7953

Answers (2)

Antonio
Antonio

Reputation: 72760

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)

Upvotes: 4

Aaron Brager
Aaron Brager

Reputation: 66252

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).

Upvotes: 27

Related Questions