【问题标题】:Swift adding a reference to the owner of an objectSwift 添加对对象所有者的引用
【发布时间】:2018-01-30 19:34:56
【问题描述】:

为简洁起见,我将使用一些简单的示例来说明我的问题。所以我目前有两个课程:

类人和类宠物

class Person:Codable {
    var name:String
    var pets:[Pet]?
}

class Pet:Codable {
    var name:String
    weak var owner:Person?
}

如果我从 json 中检索数据,我将如何添加“宠物”的所有者引用?

JSON 可能是这样的:

[  
   {  
      "name":"John",
      "pets":[  
         {  
            "name":"Meow",
            "owner":"John"
         },
         {  
            "name":"Woof",
            "owner":"John"
         }
      ]
   }
]

【问题讨论】:

  • 答案可能取决于 json。如果您编辑问题以显示一些示例 json,包括至少一个人和一只宠物,它将帮助人们帮助您。
  • @CRD 添加了一个示例 json。我也愿意更改 json 结构

标签: reference swift4 codable


【解决方案1】:

您的 JSON 是一个字典数组,每个字典代表一个人。每个人字典本身都有一个数组(与键 pets 相关联),该数组中的每个条目都是一个字典,表示该人拥有的宠物。你的问题是你如何设置你的宠物-> 人的弱链接,你没有说你试过什么。以下是一些示例伪代码,概述了您将如何处理此 JSON:

parsedJSON = ... // parse the JSON using favourite method, returning an array of dictionaries
allPeople = new Array // place to store all the people
for each personDictionary in parsedJSON // iterate over every person dictionary
   nextPerson = new Person // create a new Person
   nextPerson.name = personDictionary["name"] // set the name
   nextPerson.pets = new Array // create an array for the pets
   for each petDictionary in personDictionary["pets"] // iterate over the pets
      nextPet = new Pet // create a new Pet
      nextPet.name = petDictionary["name"] // set its name
      nextPet.owner = nextPerson       // set its owner <- answer to your question
      nextPerson.pets.add(nextPet)     // add pet to person
   end for
   allPeople.add(nextPerson) // add completed person to allPeople
end for
// at this point allPeople has all the people, and each person
// has all their pets, and each pet has an owner

现在只需在 Swift 4 中编写代码。


我也愿意更改 json 结构

上面的伪代码忽略了每个宠物的所有者字段,宠物嵌套在代表所有者的人员字典中,因此宠物中的所有者字段只是重复该信息,可以从 JSON 中删除。

在您的内部数据结构中,具有指向所有者的(弱)反向链接可能很有用,因此您可以保留它,就像上面的伪代码一样。


如果您在编写上述算法时遇到困难,请提出一个新问题,显示您编写的代码,描述您的问题所在,毫无疑问有人会帮助您。在您的新问题中添加对这个问题的引用也会很有帮助,以便人们阅读您的问题的历史以及您已经回答过的内容。

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    相关资源
    最近更新 更多