0

I have an array called People. People array contains the Person objects. I am trying to sort the array in ascending order based on the firstName.

 var people :[Person] = []

 people.sort { $0.firstName > $1.firstName }

I get the following error:

() is not convertible to [Person]
5
  • How is the array declared and initialized? Commented Oct 8, 2014 at 4:17
  • It is populated by a web service. Commented Oct 8, 2014 at 4:21
  • But how is it declared? Can you include the declaration in your question? Commented Oct 8, 2014 at 4:27
  • var people :[Person] = [] Commented Oct 8, 2014 at 4:29
  • 1
    (Again,) a complete self-contained example demonstrating the problem would have been helpful. I can see no obvious error in the code. For future readers it would be helpful to know which part of the answer solved your problem. Commented Oct 8, 2014 at 5:05

1 Answer 1

1

I believe you just need to specify the type of the array more explicitly when initializing it. This code works:

class Person {
    var firstName: String = "FirstName"
    var lastName: String = "LastName"

    init(inputFirstName: String, inputLastName: String) {
        firstName = inputFirstName
        lastName = inputLastName
    }
}
var people: [Person] = [Person]()

people.append(Person(inputFirstName: "A", inputLastName: "B"))
people.append(Person(inputFirstName: "B", inputLastName: "C"))
people.append(Person(inputFirstName: "C", inputLastName: "D"))
people.append(Person(inputFirstName: "D", inputLastName: "E"))
people.append(Person(inputFirstName: "E", inputLastName: "F"))
people.append(Person(inputFirstName: "F", inputLastName: "G"))
people.append(Person(inputFirstName: "G", inputLastName: "H"))
people.append(Person(inputFirstName: "H", inputLastName: "I"))

people.sort { $0.firstName > $1.firstName }
Sign up to request clarification or add additional context in comments.

3 Comments

var people :[Person] = [] as in the question works as well. It would be interesting to know what the actual problem was.
Strange. Yeah, I couldn't imagine why the example in the question didn't work but thought maybe that was the difference based on the error message. Maybe a version difference in Xcode/Swift?
Might be another of the notorious type inference bugs.

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.