Crash [Find the first non-consecutive number]


#1

Здравствуйте!

Задание

Your task is to find the first element of an array that is not consecutive.

By not consecutive we mean not exactly 1 larger than the previous element of the array.

E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that’s the first non-consecutive number.

If the whole array is consecutive then return null.

The array will always have at least 2 elements1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too!

Код -

func firstNonConsecutive (_ arr: [Int]) -> Int? {
var result: Int?
for i in 0..<arr.count  {
if (arr[i] + 1) != arr[i+1] {
result = arr[i+1]
break
}
else {
result = nil
}
}
return result
}
Ошибка

Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444
Current stack trace:
0 libswiftCore.so 0x00007f1ec293a610 swift_reportError + 50
1 libswiftCore.so 0x00007f1ec29adea0 swift_stdlib_reportFatalErrorInFile + 115
2 libswiftCore.so 0x00007f1ec269324e + 1397326
3 libswiftCore.so 0x00007f1ec2692da7 + 1396135
4 libswiftCore.so 0x00007f1ec2692a83 + 1395331
5 libswiftCore.so 0x00007f1ec26924f0 assertionFailure(:
:file:line:flags:) + 511
6 libswiftSwiftOnoneSupport.so 0x00007f1ec2cc3de0 specialized Array.subscript.getter + 86
7 test 0x000055ffa28cd5e1 + 38369
8 test 0x000055ffa28cdb64 + 39780
9 test 0x000055ffa28cd8c2 + 39106
10 test 0x000055ffa28cd94c + 39244
11 test 0x000055ffa28ce121 + 41249
12 libXCTest.so 0x00007f1ec2c64911 + 227601
13 libXCTest.so 0x00007f1ec2c6497c + 227708
14 libXCTest.so 0x00007f1ec2c648f4 + 227572
15 test 0x000055ffa28c9800 + 22528
16 test 0x000055ffa28cb6b4 + 30388
17 libXCTest.so 0x00007f1ec2c63270 XCTestCase.invokeTest() + 55
18 libXCTest.so 0x00007f1ec2c62f60 XCTestCase.perform(:slight_smile: + 150
19 libXCTest.so 0x00007f1ec2c66be0 XCTest.run() + 150
20 libXCTest.so 0x00007f1ec2c64e70 XCTestSuite.perform(
:slight_smile: + 160
21 libXCTest.so 0x00007f1ec2c66be0 XCTest.run() + 150
22 libXCTest.so 0x00007f1ec2c64e70 XCTestSuite.perform(:slight_smile: + 160
23 libXCTest.so 0x00007f1ec2c66be0 XCTest.run() + 150
24 libXCTest.so 0x00007f1ec2c64e70 XCTestSuite.perform(
:slight_smile: + 160
25 libXCTest.so 0x00007f1ec2c66be0 XCTest.run() + 150
26 test 0x000055ffa28c8cb9 + 19641
27 test 0x000055ffa28cd710 + 38672
28 libc.so.6 0x00007f1ec0b73ab0 __libc_start_main + 231
29 test 0x000055ffa28c870a + 18186

Я думаю и так понятно, что я максимальный новичок, поэтому я даже не до конца понимаю в чём именно состоит ошибка (краш?) и, соответственно, не могу её исправить.


#2

здесь:

arr[i+1]

вы задаете выход индекса за пределы диапазона. Поэтому пишет ошибку - Index out of range.

В строке объявления цикла добавьте - 1

for i in 0..<arr.count - 1 {
...
}

#3

Точно! Спасибо большое.


#4

you’re welcome! ))

20 символов