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]?
}
Zookeeper:
错误在此行:新动物.雇员?.动物?.append(新动物)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)
}
}
1条答案
按热度按时间lh80um4z1#
编译器推荐的解决方案有效
我从来没有见过这个错误之前,希望有人可以添加一个很好的答案解释 * 为什么 *,而不仅仅是 * 如何 *!
编辑:以下是https://github.com/apple/swift-evolution/blob/main/proposals/0176-enforce-exclusive-access-to-memory.md的原因