在swift中总结一个属性形成一个属性对象的数组

时间:2017-11-29 07:41:31

标签: ios swift realm real-mode

有两个realm对象第一类是Entry,另一个是Work。模型场景如下所示。Entry类是

open class Entry: Object {
  dynamic open var date = Entry.defaultDate()
  dynamic open var quantity = 0.0
  dynamic open var percentage = 0.0
  dynamic open var goal = 0.0
  open let gulps = List<Work>()
}

Work类看起来像这样。

open class Work: Object {
  dynamic var quantity = 0.0
  dynamic var type = 0
}

插入一些数据后,一个Entry对象看起来像这样。

(Entry {
    date = 2017-11-29;
    quantity = 1.193675890564919;
    percentage = 59.68379452824593;
    goal = 2;
    gulps = RLMArray <0x6040000e7800> (
        [0] Work {
            quantity = 0.5;
            type = 0;
        },
        [1] Work {
            quantity = 0.5;
            type = 1;
        },
        [2] Work {
            quantity = 0.09683794528245926;
            type = 0;
        },
        [3] Work {
            quantity = 0.09683794528245926;
            type = 2;
        }
    );
})

现在我正在尝试创建一个数组,其中包含根据Work类型的总数量,其中数组索引是根据Work类型的。所以此条目的数组应为。

[0.59683,0.5,0.09683794528245926]

那么如何以有效的方式生成这个数组呢?

1 个答案:

答案 0 :(得分:0)

这应该相当简单,定义一个与数量属性匹配的类型数组,然后循环返回数量的gulps数组

let workArray: [Double] = entry.gulps.map({ return $0.quantity })

map函数将迭代列表中的每个项目并运行您在大括号之间定义的闭包,在这种情况下,它将遍历每个工作项并仅返回数量。

您可以找到有关地图功能here或官方Apple文档here

的更多信息

这是我在操场上写的一个完整的工作示例

struct Entry {

    var quantity = 0.0
    var percentage = 0.0
    var goal = 0.0
    var gulps = [Work]()
}

struct Work {
    var quantity = 0.0
    var type = 0
}

let work1 = Work(quantity: 1.0, type: 5)
let work2 = Work(quantity: 2.0, type: 5)
let work3 = Work(quantity: 4.0, type: 5)
let work4 = Work(quantity: 6.0, type: 5)

let entry = Entry(quantity: 5.0, percentage: 50.0, goal: 60.0, gulps: [
    work1,
    work2,
    work3,
    work4
])

let workArray: [Double] = entry.gulps.map({ return $0.quantity })
print(workArray)
  

输出:[1.0,2.0,4.0,6.0]