Swift 4将简单数组转换为嵌套数组

时间:2018-01-05 18:14:53

标签: arrays multidimensional-array swift4

我收到一个Json feed,它被解码为一个简单的数组......我想将它转换为嵌套的多维数组。如何循环我的animalArray并将哺乳动物插入哺乳动物的语法是我的目标参见代码

import UIKit
import Foundation


// JSON is decoded to a simple Struct
struct Animals {
    var category: String
    var animalName: String
}

// simulating Animals returned to JSON
var lion = Animals(category: "wild", animalName: "lion")
var hippo = Animals(category: "wild", animalName: "hippo")
var bear = Animals(category: "wild", animalName: "bear")
var dog = Animals(category: "house", animalName: "dpg")
var cat = Animals(category: "house", animalName: "cat")
var rabbit = Animals(category: "house", animalName: "rabbit")

// simulate the  animalArry received by decoded Json
var animalArray = [Animals]()
animalArray.append(lion)
animalArray.append(hippo)
animalArray.append(dog)
animalArray.append(bear)
animalArray.append(cat)
animalArray.append(rabbit)

// Goal is to convert  animal Array to structure of mammals and mammalsArray
struct mammals {
    var animalResides: String  // (category)  wild
    var critters : [String]     // (animalName) [ lion, hippo, bear]
}
var MammalArray = [mammals]   

1 个答案:

答案 0 :(得分:0)

简短解决方案:

首先,结构名称应以大写字母和带小写字母的变量名开头。

struct Mammals {
    var animalResides: String  // (category)  wild
    var critters : [String]     // (animalName) [ lion, hippo, bear]
}

var mammalArray = [Mammals]()

将数组映射到其类别,并创建Set以获取唯一值

let categories = Set(animalArray.map{ $0.category }) // Set(["house", "wild"])

分别在类别的循环过滤器animalArray中创建Mammals实例,其类别为animalResides,过滤后的项目的映射名称为critters

for category in categories {
    let filtered = animalArray.filter({$0.category == category})
    mammalArray.append(Mammals(animalResides: category, critters: filtered.map({$0.animalName})))
}

print(mammalArray)