0

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?

2
  • 1
    If you want to modify the array that was passed in, add the inout keyword: func sort(inout source: [Int]) and call it like this sort(source: &myArray). Commented Jun 11, 2016 at 13:30
  • 1
    Be aware that the code crashes if source is nil or empty. Commented Jun 11, 2016 at 13:30

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

6 Comments

and the preferred way to write Array<Int> is [Int]
It's more common to write it as [Int], yes. Although in some rare circumstances Array<Int> does make sense.
Generic never be nil?
If you leave off the ! then it's never nil and it's much safer.
Thanks, my memory is in swift1.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.