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

标签 ios swift dictionary

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

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/

相关文章:

[String] 的 Swift 扩展?

ios - TableView 单元格内的 Collection View 未被调用

python - bool 值作为字典中的键会导致奇怪的问题吗?

ios - 在 UIViewControllerAnimatedTransitioning 委托(delegate)中,transitionContext.fromViewController 为 nil

ios - 在 Objective - C 中使用 AFNetworking 可恢复的分段文件上传

swift - 如何使 Swift 的 String 类型符合 CVarArgType 协议(protocol)?

python - 类型错误 : unhashable type: 'dict' in python

python - 具有公共(public)子键的新字典

ios - 从 iOS 应用程序在服务器上实现动态搜索的最佳方式是什么?

iphone - 奇怪的 GameKit 行为。还有其他人看到这个吗?