Ufuk Köşker
Ufuk Köşker

Reputation: 1480

Overlapping accesses to 'but modification requires exclusive access; consider copying to a local variable'

an employee can own more than one animal, but an animal must have only one employee.

First, I add an employee. Then when adding an animal, I select the employee. After selecting the employee, I press the save button. I want to transfer the animal I just added to that employee. I want to take the employee's id and add it to the employee attribute of the animal I added.

Animal Model:

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

Employee Model:

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:

Error is on this line: 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)
    }
}

Upvotes: 1

Views: 731

Answers (1)

Andrew Carter
Andrew Carter

Reputation: 334

The solution recommended by the compiler works

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
}

I've never seen this error before, hopefully someone can add a good answer explaining the why and not just the how!

EDIT: Here's the why https://github.com/apple/swift-evolution/blob/main/proposals/0176-enforce-exclusive-access-to-memory.md

Upvotes: 1

Related Questions