gpt4 book ai didi

Swift 在数组中使用自定义类型但始终打印类型名称而不是值

转载 作者:行者123 更新时间:2023-11-28 05:41:25 24 4
gpt4 key购买 nike

我有一个调用 API 的函数。当我调用指定键时,它会给我列表,我可以拿去保存到我的数组中

var car = [Car]()

我使用for循环来获取键的值

for result in fromApiResult.designatedKey {
self.car.append(Car(carName: result.Name, carType: result.Type))
}

然后我打印出 car,它看起来就像 Type

print("\(car)") // [Car,Car]

这不是我想要的,我实际上希望它看起来像下面这样

因为我会用这些数据显示在TableView上

var car = [Car(carName:"BMW",carType:"SUV")]

但是如果我在上面再次使用for循环,它可以得到正确的值

 for result in car {
print(result.carName) //"BMW"
}

我真的很新,现在擅长提问如果需要更多信息,请找我,谢谢。

最佳答案

考虑下面我找到的例子 HERE

首先您需要创建名为 CustomStringConvertible 的扩展

extension CustomStringConvertible {
var description: String {
var description: String = "\(type(of: self))("

let selfMirror = Mirror(reflecting: self)

for child in selfMirror.children {
if let propertyName = child.label {
description += "\(propertyName): \(child.value), "
}
}

description += "<\(Unmanaged.passUnretained(self as AnyObject).toOpaque())>)"

return description
}
}

然后你的类(class)需要像这样确认扩展:

class Person: CustomStringConvertible {
let name: String
let age: Int

init (name: String, age: Int) {
self.name = name
self.age = age
}
}

现在您可以在控制台中打印您的对象,如:

let alex = Person(name: "Alex", age: 20)
print(alex) // Person(name: Alex, age: 20, <0x000060c000058d20>)

有关更多信息,请阅读 HERE .

关于Swift 在数组中使用自定义类型但始终打印类型名称而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56591748/

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