2

I am trying to implement common alghorithm in Swift.

Even though I did not define numbers as a let variable, but I am getting following error:

cannot assign through subscript: 'numbers' is a 'let' constant numbers[i] = maxNumber

My Implementation is as follows:

func InsertionSort (numbers : [Int]) -> [Int]
{
    var maxNumber  = 0
    var j = 0
    var size = numbers.count-1

    for (i,number) in numbers.enumerated()
    {
        j = i + 1
        for index in j...size
        {
            if numbers[index] > number
            {
                maxNumber = numbers[index]
                numbers[index] = numbers[i]
                // error is thrown in the following line
                numbers[i] = maxNumber
            }
        }
    }

    return numbers
}
casillas
  • 16,351
  • 19
  • 115
  • 215
  • 1
    Possible duplicate of [Modifying an array passed as an argument to a function in Swift](https://stackoverflow.com/questions/45640752/modifying-an-array-passed-as-an-argument-to-a-function-in-swift) – Rakesha Shastri Oct 16 '18 at 06:20
  • 1
    Function parameters are constant by default. – Rakesha Shastri Oct 16 '18 at 06:21
  • @RakeshaShastri Although that question's answer works here, I don't think that is the best solution in this situation. – Sweeper Oct 16 '18 at 06:24
  • @Sweeper depending on what he does with the returned value he can either use your answer or `inout` parameters. – Rakesha Shastri Oct 16 '18 at 06:27
  • Possible duplicate of [Cannot assign through subscript: 'dict' is a 'let' constant](https://stackoverflow.com/questions/47310863/cannot-assign-through-subscript-dict-is-a-let-constant) – Tamás Sengel Oct 17 '18 at 00:13

1 Answers1

2

Parameters are immutable by default. To make a parameter mutable, you need to add an inout modifier.

However, seeing that your method returns an array, you probably don't want the parameter to be modified as well. You should instead make a copy of the parameter, modify that, and return the copy:

func InsertionSort (numbers : [Int]) -> [Int]
{
    var maxNumber  = 0
    var j = 0
    let size = numbers.count-1
    var numbersCopy = numbers // <------ note this line

    for (i,number) in numbers.enumerated()
    {
        j = i + 1
        for index in j...size
        {
            if numbers[index] > number
            {
                maxNumber = numbers[index]

                // note how I modified the copy here
                numbersCopy[index] = numbers[i]
                numbersCopy[i] = maxNumber
            }
        }
    }

    return numbersCopy
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313