0

In the following code, is it necessary to have unowned if the Swift array is passed by value ?

Category has a property for a Swift array, not an Item, so unowned is not necessary right?

final class Item: Base {

    unowned let category: Category

    init(value: Int, category: Category) {
        self.category = category
        super.init(value: value)
    }
}

final class Category: Base {

    var items: [Item] = []

}

class Base {

    let name: String

    var index: Int {
        return Int(name)!
    }

    init(name: String) {
        self.name = name
    }

    init(value: Int) {
        self.name = String(value)
    }
}
Jonesy
  • 195
  • 8

1 Answers1

1

You still need unowned or weak. There's nothing special about arrays that prevents them from being involved in retain cycles.

Arrays simply allow you to reference multiple objects. myCatgeory.items can have one element, which is an Item that has a category that references myCategory:

let myCategory = Category()
let item = Item(value: 0, category: myCategory)
myCategory.items = [item]
// retain cycle!
Sweeper
  • 213,210
  • 22
  • 193
  • 313