Leo Leo - 2 years ago 189
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download