[英]NSArray Sort Function on Swift
I have an array called People. 我有一个名为People的数组。 People array contains the Person objects.
People数组包含Person对象。 I am trying to sort the array in ascending order based on the firstName.
我试图基于firstName以升序对数组进行排序。
var people :[Person] = []
people.sort { $0.firstName > $1.firstName }
I get the following error: 我收到以下错误:
() is not convertible to [Person]
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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.