Leo
Leo

Reputation: 865

How to change the element of array in swift

I'm having difficulty with this function:

func sort(source: Array<Int>!) -> Array<Int>! {
   source[0] = 1
    ......
    return source
}

An error happens:

enter image description here

Why can't I directly assign the value to the specific element in the array?

Upvotes: 0

Views: 123

Answers (1)

user887210
user887210

Reputation:

The variable sort is immutable because it's a parameter. You need to create a mutable instance. Also, there's no reason to have the parameter and return value as implicitly unwrapped optionals with the ! operator.

func sort(source: Array<Int>) -> Array<Int> {
   var anotherSource = source // mutable version
   anotherSource[0] = 1
   ......
   return anotherSource
}

Upvotes: 1

Related Questions