gpt4 book ai didi

swift - 如何返回一个数组?

转载 作者:行者123 更新时间:2023-11-28 10:27:34 30 4
gpt4 key购买 nike

我试图返回一个包含所有变量的数组。所以我可以将所有内容存储在一个数组中。我该如何修复我的代码,以便将所有内容都放入一个数组中?

func getFriendRecord () -> [String] {
var info = ""
let fetchRequest: NSFetchRequest<Friend> = Friend.fetchRequest()
do {
let searchResults = try getContext().fetch(fetchRequest)
for trans in searchResults as [NSManagedObject] {
let firstName = String(trans.value(forKey: "firstName") as! String)
let lastName = String(trans.value(forKey: "lastName") as! String)
let gender = String(trans.value(forKey: "gender") as! String)
let age = String(trans.value(forKey: "age") as! String)
let address = String(trans.value(forKey: "address") as! String)
info = info + firstName + ", " + lastName + ", " + gender + ", " + age + ", " + address + "\n"
}
} catch {
print("Error with request: \(error)")
}
return info
}

最佳答案

如果你想返回一个数组,那么info应该是一个数组:

var info: [String] = []

然后您将向该数组添加其他元素:

let record = [firstName, lastName, gender, age, address].joined(separator: ", ") + "\n"
info.append(record)

我已将其更改为 joined,因为您应该避免在表达式中使用多个 +。在 Swift 中,由于与重载相关的不明显原因,编译速度极慢。没什么问题,只是效果不好。您也可以在这里使用字符串插值,这完全没问题(甚至可能更好一点):

let record = "\(firstName), \(lastName), \(gender), \(age), \(address)\n"

关于swift - 如何返回一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58054403/

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