swiftPunk
swiftPunk

Reputation: 1

Can I remove some element from a Range in Swift?

I have a ClosedRange from 1 to 10, I wanted to know can we remove some element of it? like removing 5 and 7 from that closedRange then we should have: 1 2 3 4 6 8 9 10 instead of having 1 2 3 4 5 6 7 8 9 10

let closedRange: ClosedRange<Int> = 1...10

Upvotes: 0

Views: 529

Answers (2)

user652038
user652038

Reputation:

Like the other answer states, no. symmetricDifference is good for this.

([5, 7] as Set).symmetricDifference(1...10)

Upvotes: 0

jnpdx
jnpdx

Reputation: 52397

It ends up being an array of type [ClosedRange<Int>.Element] because once you remove elements, it's not a range any more (since by definition it doesn't include all the elements between the bounds).

From the Apple docs (https://developer.apple.com/documentation/swift/closedrange):

An interval from a lower bound up to, and including, an upper bound.

let closedRange: ClosedRange<Int> = 1...10
let closedRangeArrayWithElementsMissing = closedRange.filter { $0 != 5 && $0 != 7 }
// = [1, 2, 3, 4, 6, 8, 9, 10]

Upvotes: 2

Related Questions