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

**URL:** https://forum.crystal-lang.org/t/cant-swap-values-in-an-array-because-i-didnt-comprehend-the-error/576
**Category:** Help & Support
**Created:** [March 21, 2019, 10:57am UTC](https://forum.crystal-lang.org/t/cant-swap-values-in-an-array-because-i-didnt-comprehend-the-error/576 "2019-03-21T10:57:09Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![girng](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/girng/32/127_2.png) [@girng](https://forum.crystal-lang.org/u/girng)
#### Post date: [March 21, 2019, 10:57am UTC](https://forum.crystal-lang.org/t/cant-swap-values-in-an-array-because-i-didnt-comprehend-the-error/576/1 "2019-03-21T10:57:09Z")

</div>

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

```auto
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:

```auto
puts ids.swap(3, 0)

```

That works fine.  
Am I doing this wrong?

---

<div class="post-metadata">

### Author: ![girng](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/girng/32/127_2.png) [@girng](https://forum.crystal-lang.org/u/girng)
#### Post date: [March 21, 2019, 11:06am UTC](https://forum.crystal-lang.org/t/cant-swap-values-in-an-array-because-i-didnt-comprehend-the-error/576/2 "2019-03-21T11:06:50Z")

</div>

```auto
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:

```auto
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

---

<div class="post-metadata">

### Author: ![straight-shoota](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/straight-shoota/32/36_2.png) [@straight-shoota](https://forum.crystal-lang.org/u/straight-shoota)
#### Post date: [March 21, 2019, 11:28am UTC](https://forum.crystal-lang.org/t/cant-swap-values-in-an-array-because-i-didnt-comprehend-the-error/576/3 "2019-03-21T11:28:36Z")

</div>

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

```nohighlight
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)

```
