[英]Swift - shorter way write the attached code?
我有以下代码:
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
}
}
}
}
}
有没有更短的书写方式? 也许甚至跳过嵌套的循环?
您可以使用功能性方法。
customerDevices.forEach { device in
device.deviceAttribute = attributes.last(where: { $0.customerDeviceId == device.customerDeviceId })
}
这样的事情应该做的工作
customerDevices.forEach { (customerDevice) in
customerDevice.deviceAttribute = attributes.compactMap({ (attribute) -> DeviceAttribute? in
return attribute.customerDeviceId == customerDevice.customerDeviceId ? attribute : nil
}).first
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.