数组的俱乐部价值

时间:2019-04-22 09:19:48

标签: ios swift

我正在使用 Swift 4.2 编写 iOS应用。 我正在获取JSON数组,该数组将转换为 Sector

类的Swift对象

JSON:

"Sector": [
            {
                "REPSECTOR": "TELECOM - SERVICES",
                "PERC_HOLD": 5.6,
                "CO_NAME": "REVERSE REPO"
            },
            {
                "REPSECTOR": "TELECOM - SERVICES",
                "PERC_HOLD": 1.0,
                "CO_NAME": "BHARTI AIRTEL"
            },
            {
                "REPSECTOR": "FERROUS METALS",
                "PERC_HOLD": 0.3,
                "CO_NAME": "COAL INDIA"
            }
        ]

班级

class Sector{
  var REPSECTOR:String=""
  var PERC_HOLD:Double=0.0
  var CO_NAME:String=""
}

我正在从上方制作类型为 [Sector] 的Array array1。

我需要从上面的数组中创建一个新数组,该数组必须基于 REPSECTOR 变量以及PERC_HOLD的总和进行合并/组合。

预期结果:

具有2个元素的新数组: 1:电信-服务,5.6 + 1.0 2:含铁量0.3

4 个答案:

答案 0 :(得分:0)

假设您解码的数组称为array

var array: [Sector]()

让我们创建一个具有相同REPSECTOR属性的扇区的字典:

let dict = Dictionary(grouping: array) {
    $0.REPSECTOR
}

现在,让我们创建一个具有相同名称的扇区的新数组,并对它们的PERC_HOLD求和:

var newArray = [Sector]()
for (key, value) in dict {
    let sector = Sector()
    sector.REPSECTOR = key
    sector.PERC_HOLD = value.reduce(0, { $0 + $1.PERC_HOLD })
    newArray.append(sector)
}

您可以通过以下方式检查结果:

for s in newArray {
    print(s.CO_NAME, s.PERC_HOLD)
}

答案 1 :(得分:0)

首先,我认为您应该在Sector类型中使用正确的大小写,并使用Codable。对于您的类型,这是微不足道的:

struct Sector: Codable {
    let repsector: String
    let percHold: Double
    let coName: String

    enum CodingKeys: String, CodingKey {
        case repsector = "REPSECTOR"
        case percHold = "PERC_HOLD"
        case coName = "CO_NAME"
    }
}

然后,假设我们拥有这样的JSON:

let sectorsJSON = """
[
  {
    "REPSECTOR": "TELECOM - SERVICES",
    "PERC_HOLD": 5.6,
    "CO_NAME": "REVERSE REPO"
  },
  {
    "REPSECTOR": "TELECOM - SERVICES",
    "PERC_HOLD": 1.0,
    "CO_NAME": "BHARTI AIRTEL"
  },
  {
    "REPSECTOR": "FERROUS METALS",
    "PERC_HOLD": 0.3,
    "CO_NAME": "COAL INDIA"
  }
]
""".data(using: .utf8)!

然后我们可以像这样解码您的JSON:

let decoder = JSONDecoder()
let rawSectors = try decoder.decode([Sector].self, from: sectorsJSON)

然后我们可以按.repsector对其进行分组并总结百分比:

let groupedSectors = Dictionary(grouping: rawSectors, by: { $0.repsector })
    .map { (arg) -> (String, Double) in
        let (key, value) = arg
        let percents = value.reduce(into: 0, { (acc, sector) in
            acc += sector.percHold
        })
        return (key, percents)
}

print(groupedSectors) // [("FERROUS METALS", 0.3), ("TELECOM - SERVICES", 6.6)]

答案 2 :(得分:0)

 let dicSector = ["Sector": [
        [
            "REPSECTOR": "TELECOM - SERVICES",
            "PERC_HOLD": 5.6,
            "CO_NAME": "REVERSE REPO"
        ],
        [
            "REPSECTOR": "TELECOM - SERVICES",
            "PERC_HOLD": 1.0,
            "CO_NAME": "BHARTI AIRTEL"
        ],
        [
            "REPSECTOR": "FERROUS METALS",
            "PERC_HOLD": 0.3,
            "CO_NAME": "COAL INDIA"
        ]
        ]]

可编码部门

class Sector: Codable {
    var REPSECTOR:String=""
    var PERC_HOLD:Double=0.0
    var CO_NAME:String=""
}

将字典转换为对象数组

    var arraySector = [Sector]()
    if let array = dicSector["Sector"] {
        do {
            let data = try JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted)
            let jsonDecoder = JSONDecoder()
            arraySector = try jsonDecoder.decode([Sector].self, from: data)
        }
        catch {
            print(error.localizedDescription)
        }

    }

要分组的数组

    let predicate = { (element: Sector) in
        return element.REPSECTOR
    }

    let dic = Dictionary(grouping: arraySector, by: predicate)
    print(dic)

输出

  

[“电信-服务”:[部门,部门],“ FERROUS   金属”:[部门]]

答案 3 :(得分:0)

这不是最好的解决方案,但是可行

var newArray = [Sector]()

    oldArray.forEach() { element in
        if newArray.contains(where: { $0.REPSECTOR == element.REPSECTOR }) {
            newArray.forEach() { newElement in
                if newElement.REPSECTOR == element.REPSECTOR {
                    newElement.CO_NAME + element.CO_NAME
                } else {
                    newArray.append(element)
                }
            }
        } else {
            newArray.append(element)
        }
    }