gpt4 book ai didi

ios - 如何使用 Swift 类在数组中添加信息

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:52 25 4
gpt4 key购买 nike

我在向数组中添加一些信息时遇到了问题。

我的类 Flights 由以下定义:

class Flight{
let date: String
let type: String
let regi: String

let totalTime: String

let depTime: String
let depPlace: String

let arrTime: String
let arrPlace: String

init(from dat: String, _ typ: String, _ reg: String, _ totaltim: String, _ depTim: String, _ depPlac: String, _ arrTim: String, _ arrPlac: String) {
self.date = dat
self.type = typ
self.regi = reg

self.totalTime = totaltim

self.depTime = depTim
self.depPlace = depPlac

self.arrTime = arrTim
self.arrPlace = arrPlac
}}

在我的主要代码中,我已经像这样声明了我的数组:

var datas: [Flight] = []

最后我用这段代码添加了一些来自 firebase 的信息:(我添加了一些注释来向您展示 print() 结果)

if let user = Auth.auth().currentUser{
// user is connect
let ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid

let ev = ref.child("flights").child(userID!)

ev.observe(.childAdded, with: { (snapshot) -> Void in
let flightKey = snapshot.key

ref.child("flights").child(userID!).child(flightKey).observeSingleEvent(of: .value) {(snapshot) in
let value = snapshot.value as? NSDictionary

let date = value?["Date"] as? String ?? "no date"
let type = value?["aircraft-model"] as? String ?? "no type"
let registration = value?["aircraft-registration"] as? String ?? "no callsign"
let totalTime = value?["TOTAL-TIME"] as? String ?? "no total Time"
let deppartTime = value?["departure-time"] as? String ?? "no departure Time"
let deppartPlace = value?["departure-place"] as? String ?? "no departure Place"
let arrivalTime = value?["arrival-time"] as? String ?? "no arrival Time"
let arrivalPlace = value?["arrival-place"] as? String ?? "no arrival Place"

print("Date : \(date) - type : \(type) - registration : \(registration) - Etc ...")// Give me exactly the value I requested


self.datas.append(Flight(from: date, type, registration, totalTime, deppartTime, deppartPlace, arrivalTime, arrivalPlace))


print(self.datas)// Give me "MyProjectName.Flight ...
}

})

}else{
// si non connecté alors DECONNEXION !!!!
fatalError("error ...")
}

所以我不明白为什么如果我打印从 firebase 接收到的值它可以工作但是如果我打印由 firebase 接收到的值完成的数组值它不起作用?

感谢您的帮助!

传单 74

最佳答案

欢迎 :)

我认为一切都如预期的那样,你看到这个只是因为 Swift 不知道如何描述你的对象。

要解决此问题,您应该在 Flight 类 ( https://developer.apple.com/documentation/swift/customstringconvertible ) 中实现 CustomStringConvertible 协议(protocol)

有点像

extension Flight: CustomStringConvertible {
var description: String {
var description = ""
description.append("date: \(date)\n")
description.append("type: \(type)\n")
description.append("regi: \(regi)\n")
//and so on
return description
}
}

应该给你你正在寻找的东西。

希望对你有帮助

关于ios - 如何使用 Swift 类在数组中添加信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53140455/

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