将字典中的值分配给结构

时间:2018-12-18 07:54:22

标签: 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中??

3 个答案:

答案 0 :(得分:2)

首先,从不将属性或结构成员声明为隐式未包装的可选变量,这些可选变量在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)
    }
} 

答案 1 :(得分:0)

我假设您希望与description键关联的值成为您的details结构中属性CricketerDetail的值。

您只需使用键访问字典并将其转换为适当的类型:

cricketerDetailList.append(
    CricketerDetail(image: item["image"] as! UIImage,
                    name: item["name"] as! String,
                    details: item["description"] as! String))

答案 2 :(得分:0)

let allCricketerDetailList = generateCricketerDetailList()
//inside for loop
let detail = CricketerDetail(name: allCricketerDetailList["name"] as! String.........)

但是我的建议是使用双数字初始化struct。 例如

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

  init(dict: [String:Any]) {
    self.image = dict["image"] as? UIImage ?? UIImage()
    self.name = dict["name"] as? String ?? ""
    self.details = dict["description"] as? String ?? ""
  }
}

像这样设置结构后,将如下所示初始化结构:

//for loop
cricketerDetailList.append(CricketerDetail(dict: item) //item is coming from your loop