对'but modification requires exclusive access; consider copying to a local variable'的重叠访问



一个employee可以有多个animal,但一个animal只能有一个employee

首先,我添加一个雇员。然后在添加动物时,选择雇员。选择员工后,我按下保存按钮。我想转移我刚刚加到那个员工身上的动物。我想获取雇员的id,并将其添加到我添加的动物的雇员属性中。

动物模型:

struct Animal {
let id: String?
var name: String?
var sound: String?
var age: Double?
var waterConsumption: Double?
var employee: Employee?
var animalType: String?
}

员工模型:

struct Employee {
let id: String?
var name: String?
var lastName: String?
var age: Int?
var gender: String?
var salary: Double?
var experienceYear: String?
var animals: [Animal]?
}

ZooManager:

错误出现在这一行:newAnimal.employee?.animals?.append(newAnimal)Overlapping accesses to 'newAnimal.employee', but modification requires exclusive access; consider copying to a local variable

protocol ZooManagerProtocol {
var animals: [Animal] { get set }
var employees: [Employee] { get set }

func addNewAnimal(_ model: Animal)
}
class ZooManager: ZooManagerProtocol {
static var shared = ZooManager()

var animals: [Animal] = []
var employees: [Employee] = []

private init() { }

func addNewAnimal(_ model: Animal) {
var newAnimal = model
guard var employee = employees.filter({ $0.id == model.employee?.id }).first else { return }
newAnimal.employee = employee
newAnimal.employee?.animals?.append(newAnimal)
dump(newAnimal)
}

func addNewEmployee(_ model: Employee) {
employees.append(model)
}
}

编译器推荐的解决方案

func addNewAnimal(_ model: Animal) {
var newAnimal = model
guard var employee = employees.filter({ $0.id == model.employee?.id }).first else { return }
employee.animals?.append(newAnimal)
newAnimal.employee = employee
}

我以前从未见过这个错误,希望有人能提供一个好的答案,解释为什么,而不仅仅是如何!

编辑:以下是原因https://github.com/apple/swift-evolution/blob/main/proposals/0176-enforce-exclusive-access-to-memory.md

相关内容

最新更新