简体   繁体   中英

I'm trying to make a function to sort ints in an array but i get an error when this code is being ran. Where is my error?

I know that there is a sort property in an array but i was trying to figure out how it was made.

var array = [3,6,9,2,1,5,7,4,8]

func sort() {

    for n in array {

        if n < array[array.indexOf(n)! + 1] {

            print("do nothing")


        } else  {

            array[n] = array[n + 1]
            array[n + 1] = array[n]
        }
    }


}

sort()

You've got an index out of bounds error that comes from this line

if n < array[array.indexOf(n)! + 1] 

When n reaches the end of the array, you're trying to access the next element in the array, which doesn't exist because you've already reached the end.

You'll need to check to make sure that it is within the bounds of the array before you access the next element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM