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.
for index2 in index1+1...length
but say for an 8-element array wouldn’t length be 7, so index1+1 can be 8 since ranges are inclusive and the first loop is 0-7?for
statement,if
statements don’t require parentheses either.for
orif
(and others), nor semicolons. As a coder, you get to choose your style. Just be consistent about it. Always use them or never use them. Of course it's less typing if you choose not to use the optional syntax.