gpt4 book ai didi

ios - 将字典中的值分配给结构

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

我有一个这样给出的结构......

struct CricketerDetail {
var image: UIImage!
var name: String!
var details: String!

init(image: UIImage, name: String, details: String) {
self.image = image
self.name = name
self.details = details
}
}

现在我有一个这样给出的函数...

enter image description here

在屏幕截图中,Common2 给出为,

class Common2: NSObject {

class func generateCricketerDetailList() -> [[String:Any]] {
return [["name": "Sachin Tendulkar","description":"add descr. here","image": UIImage(named: "Sachin.jpeg")!],["name":"Sourav Ganguly","description":"add descr. here","image":UIImage(named: "sourav.jpeg")!],["name":"Adam Gilchrist","description":"add descr. here","image":UIImage(named: "adam.jpeg")!],["name":"Jonty Rhodes","description":"add descr. here","image":UIImage(named: "adam.jpeg")!],["name":"Wasim Akram","description":"add descr. here","image":UIImage(named: "wasim.jpg")!]]
}
}

现在我如何将这本词典的图像、名称和详细信息具体添加到数组 cricketerDetailList 中,如屏幕截图中所示......?

最佳答案

首先,永远不要将属性或结构成员声明为在 init 方法中使用非可选值初始化的隐式解包可选值。

删除感叹号。

struct CricketerDetail {
var image: UIImage
var name: String
var details: String

...

将一种类型映射到另一种类型的最有效方法是使用 map

func getAllCricketerDetailList() -> [CricketerDetail] {
return Common2.generateCricketerDetailList().map { item -> CricketerDetail in
CricketerDetail(image: item["image"] as! UIImage, name: item["name"] as! String, details: item["description"] as! String)
}
}

关于ios - 将字典中的值分配给结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53828522/

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