Why can't I change the the "numbers" array using subscripts when "Foo" is an implicitly unwrapped optional?
struct Foo { var numbers = [0,0,0] subscript(index: Int) -> Int { get { return self.numbers[index] } set { self.numbers[index] = newValue } } } var fooA:Foo! fooA = Foo() fooA[1] = 1 // does not change numbers array fooA[1] // returns 0 fooA.numbers[1] = 1 // this works fooA[1] // returns 1 var fooB:Foo! fooB = Foo() fooB![1] = 1 // this works fooB![1] // returns 1
For some reason it works when I make "Foo" a class (called "Goo" below)
class Goo { var numbers = [0,0,0] subscript(index: Int) -> Int { get { return self.numbers[index] } set { self.numbers[index] = newValue } } } var goo:Goo! goo = Goo() goo[1] = 1 // this works goo[1] // returns 1