-2
struct Numbers {
    var list: [String] = [
        "one",
        "two",
        "three"
    ]
    
    func returnList() -> [String] {
        var sortedList: [String] = self.list.sorted()
        var finalList: [String] = sortedList.insert("four", at: 0)
        return finalList
    }
}

finalList is inferred to be a () instead of [String]. If I specify the type [String] I get the message:

Cannot convert value of type '()' to specified type '[String]'

Why on earth?

Robert Brax
  • 6,508
  • 12
  • 40
  • 69
  • 4
    Because `insert` returns `Void` aka `()` and modifies the array inplace? Just remove the `finalList` variable and return `sortedList`. – Clashsoft Apr 16 '21 at 07:03
  • See [this very similar question](https://stackoverflow.com/q/66452912/5133585) about `append` rather than `insert`, or [this question](https://stackoverflow.com/q/66649002/5133585) about `subtract`. – Sweeper Apr 16 '21 at 07:04

1 Answers1

0

You’ve misunderstood the error message.

The problem is that sortedList.insert does not return a value. (We express this by saying it returns ().) Hence it cannot be assigned to finalList: [String], for the simple reason that it is not a [String].

So just change

var sortedList: [String] = self.list.sorted()
var finalList: [String] = sortedList.insert("four", at: 0)
return finalList

To

var sortedList: [String] = self.list.sorted()
sortedList.insert("four", at: 0)
return sortedList
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I grant that it can be a little confusing knowing which Swift methods return a value and which ones operate directly on a mutable target. Your code exemplifies both. – matt Apr 16 '21 at 07:21