gpt4 book ai didi

swift - Swift 上的 NSArray 排序函数

转载 作者:行者123 更新时间:2023-11-30 10:21:35 25 4
gpt4 key购买 nike

我有一个名为 People 的数组。 People 数组包含 Person 对象。我试图根据名字按升序对数组进行排序。

 var people :[Person] = []

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

我收到以下错误:

() is not convertible to [Person]

最佳答案

我相信您只需要在初始化数组时更明确地指定数组的类型。此代码有效:

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 }

关于swift - Swift 上的 NSArray 排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26249117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com