更新通过引用传递的数组中的项目
Updating an item in an array passed by reference
更新数组中的项目的 easiest/right 方法是什么?我希望调用者也有更新的数组。所以:
static func updateItem(updatedItem: Item, inout items: [Item]) -> Bool {
var item = items.filter{ [=10=].id == updatedItem.id }.first
if item != nil {
item = updatedItem
return true
}
return false
}
我希望来电者有更新的项目(带有更新的项目)。我认为上面代码的问题在于它只更新了局部变量项。实际更新 items 数组中相关项目的最佳方法是什么?
您正在改变 item
,它只是数组中实例的副本(如果 Item
是值类型,例如 struct
、tuple
, 或 enum
), 或对它的引用(如果 Item
是引用类型,例如 `class)。无论哪种情况,阵列都不会受到影响。
您需要在数组中找到实例的索引,然后在该索引处改变数组。
func updateItem(updatedItem: Item, inout items: [Item]) -> Bool {
guard let index = items.index(where: { [=10=].id == updatedItem.id }) else {
return false // No matching item found
}
items[index] = updatedItem
return true
}
不过,这一切都相当笨拙。如果您改用字典,将 id
映射到具有 id
的实例会更好。这意味着您将拥有快速、恒定的时间查找,而且会更加方便。下面是它的外观:
// Assuming the "id" is an Int
func updateItem(updatedItem: Item, items: inout [Int: Item]) -> Bool {
return items.updateValue(updatedItem, forKey: updatedItem.id) != nil
}
就像超人穿上他的紧身衣一样——一次一条腿。循环传入的 inout
数组并替换 id
匹配的任何项目:
func updateItem(updatedItem: Item, items: inout [Item]) -> Bool {
var result = false
for ix in items.indices {
if items[ix].id == updatedItem.id {
items[ix] = updatedItem
result = true
}
}
return result
}
请注意,这是 Swift 3 语法,其中 inout
位于类型之前,而不是标签。
你可以多写一点"Swiftily"使用map
:
func updateItem(updatedItem: Item, items: inout [Item]) {
items = items.map {
[=11=].id == updatedItem.id ? updatedItem : [=11=]
}
}
...但最终结果是一样的。
更新数组中的项目的 easiest/right 方法是什么?我希望调用者也有更新的数组。所以:
static func updateItem(updatedItem: Item, inout items: [Item]) -> Bool {
var item = items.filter{ [=10=].id == updatedItem.id }.first
if item != nil {
item = updatedItem
return true
}
return false
}
我希望来电者有更新的项目(带有更新的项目)。我认为上面代码的问题在于它只更新了局部变量项。实际更新 items 数组中相关项目的最佳方法是什么?
您正在改变 item
,它只是数组中实例的副本(如果 Item
是值类型,例如 struct
、tuple
, 或 enum
), 或对它的引用(如果 Item
是引用类型,例如 `class)。无论哪种情况,阵列都不会受到影响。
您需要在数组中找到实例的索引,然后在该索引处改变数组。
func updateItem(updatedItem: Item, inout items: [Item]) -> Bool {
guard let index = items.index(where: { [=10=].id == updatedItem.id }) else {
return false // No matching item found
}
items[index] = updatedItem
return true
}
不过,这一切都相当笨拙。如果您改用字典,将 id
映射到具有 id
的实例会更好。这意味着您将拥有快速、恒定的时间查找,而且会更加方便。下面是它的外观:
// Assuming the "id" is an Int
func updateItem(updatedItem: Item, items: inout [Int: Item]) -> Bool {
return items.updateValue(updatedItem, forKey: updatedItem.id) != nil
}
就像超人穿上他的紧身衣一样——一次一条腿。循环传入的 inout
数组并替换 id
匹配的任何项目:
func updateItem(updatedItem: Item, items: inout [Item]) -> Bool {
var result = false
for ix in items.indices {
if items[ix].id == updatedItem.id {
items[ix] = updatedItem
result = true
}
}
return result
}
请注意,这是 Swift 3 语法,其中 inout
位于类型之前,而不是标签。
你可以多写一点"Swiftily"使用map
:
func updateItem(updatedItem: Item, items: inout [Item]) {
items = items.map {
[=11=].id == updatedItem.id ? updatedItem : [=11=]
}
}
...但最终结果是一样的。