0

I am getting this error 'weak' may only be applied to class and class-bound protocol types, not '[ExerciseSet]' when trying to make a custom array object to weak. Why can't I assign weak to this type?

class Session {
    weak var sets: [ExerciseSet]?    
    
}
Noah Iarrobino
  • 1,435
  • 1
  • 10
  • 31

1 Answers1

2

You can't do this because Swift Arrays are structs, not classes. If you want to have a weak reference to an array in Swift, you will need to use a wrapper object like so:

class Wrapper<T> {
   let value: T
}

then change your class to the following:

class Session {
   weak var sets: Wrapper<[ExerciseSet]?>
}

That being said, it probably doesn't make sense to use a weak reference here. Your session is probably either a singleton or an object that stays in memory your entire application lifecycle.

Unless you actually need to know whether the property was set or not, you can also probably use [ExerciseSet] instead of making it optional, then use an empty array when you don't have any values.

AdamPro13
  • 7,232
  • 2
  • 30
  • 28
  • when the user completes a session that data is saved to CoreData, and then all the session are organized in a tableView, in that case would it be better to make the sets a weak var? – Noah Iarrobino Sep 28 '20 at 23:24