Can't swap values in an array, because I didn't comprehend the error

#1

I’m stumped on this: https://play.crystal-lang.org/#/r/6jd1/edit

ids = [3, 1, 2, 5]


index_to_swap = ids.index(5)

puts index_to_swap

puts ids.swap(index_to_swap, 0)

Basically, if I use index_to_swap as the first parameter, there is an error. But if a literal integer is used:

puts ids.swap(3, 0)

That works fine.
Am I doing this wrong?

0 Likes

#2
if index_to_swap = ids.index(5)
 puts ids.swap(index_to_swap, 0)
end

This works! Just did some trial and error. But how come?

index_to_swap is set to 3

Example:

ids = [3, 1, 2, 5]


index_to_swap = 3

puts index_to_swap

puts ids.swap(index_to_swap, 0)

Works

Is it because the index method has a possibility of returning nil?

Edit, seems so

in /usr/lib/crystal/array.cr:1701: undefined method ‘<’ for Nil (compile-time type is (Int32 | Nil))

Sorry about that. Edited title, /facepalm

0 Likes

#3

Array#swap should restrict the arguments to Int, then the error would be more clear:

no overload matches 'Array#swap' with types (Int32 | Nil), Int32
Overloads are:
 - swap(a : Int, b : Int)
Couldn't find overloads for these types:
 - swap(a : Nil, b : Int32)
0 Likes