Comparing an array element to a value throws an error

I'm not sure what I am doing wrong, but when I execute the code below:
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
let length = nums.count-1;
for index1 in 0...length {
let difference = target - nums[index1];
print(target, difference, nums[index1])
if (nums[index1] < difference) {
for index2 in index1+1...length {
if (nums[index2] == difference) {
return [index1, index2];
}
}
}
}
return [];
}
let summer = twoSum([-1,-2,-3,-4,-5], -8)
I get the following error:
Swift/ClosedRange.swift:347: Fatal error: Range requires lowerBound <= upperBound
Interestingly, if I change the condition for the if statement to
nums[index1] <= target
, it doesn't crash.
Answer
The issue is that in your inner for-loop, when index
equals length
, your inner loop becomes: for index2 in index1+1...length
.
This is equivalent to for index2 in nums.count ... nums.count - 1
. As the error says, the beginning of a loop range can't be larger than the end of the range.
Solution: You can just change if (nums[index1] < difference)
to index1 + 1 <= length
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles