斯威夫特-写附件代码的捷径?

时间:2019-03-18 10:18:11

标签: swift

我有以下代码:

class Device{
    var customerDeviceId:Int!
    var attribute:DeviceAttribute!
}

class DeviceAttribute{
    var customerDeviceId:Int!
}

class MainClass{
   var devices:[Device]!

   private func handleDeviceAttributes(_ attributes:[DeviceAttribute])  {
    for attribute in attributes {
        for device in devices {
            if device.customerDeviceId == attribute.customerDeviceId {
                device.attribute = attribute
            }
         }
      }
    }
 }

有没有更短的书写方式?甚至可以跳过嵌套的for循环?

2 个答案:

答案 0 :(得分:3)

您可以使用功能性方法。

customerDevices.forEach { device in
    device.deviceAttribute = attributes.last(where: { $0.customerDeviceId == device.customerDeviceId })
}

答案 1 :(得分:1)

类似的事情应该可以完成

customerDevices.forEach { (customerDevice) in
        customerDevice.deviceAttribute = attributes.compactMap({ (attribute) -> DeviceAttribute? in
            return attribute.customerDeviceId == customerDevice.customerDeviceId ? attribute : nil
        }).first
    }