-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?

2
  • 4
    Because insert returns Void aka () and modifies the array inplace? Just remove the finalList variable and return sortedList. Commented Apr 16, 2021 at 7:03
  • See this very similar question about append rather than insert, or this question about subtract. Commented Apr 16, 2021 at 7:04

1 Answer 1

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

1 Comment

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.

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.