Leo Leo - 5 months ago 12
iOS Question

How to change the element of array in swift

In Swift3:

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

An error happen:

enter image description here

Cannot assign the value to the special element for the array directly?


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