Swift添加对对象所有者的引用

时间:2018-01-30 19:34:56

标签: reference swift4 codable

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

班级人员和班级宠物

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

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

如果从json检索数据,如何添加“Pet”的所有者引用?

JSON可能是这样的:

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

1 个答案:

答案 0 :(得分:0)

您的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