Subscript of a struct doesn't set values when created as an implicitly unwrapped optional

孤人 提交于 2019-12-21 06:19:30

问题


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

回答1:


it looks like a bug (or i miss something important), check this

struct Foo {
    var numbers = [0,0,0]
    subscript(index: Int) -> Int {
        get {
            return self.numbers[index]
        }
        set {
            numbers[index] = newValue
        }
    }
}


var fooA:Foo! = Foo()
// here is the difference
fooA?[1] = 1
fooA[1]                  //  1
fooA.numbers[1] = 1
fooA[1]                  //  1

more 'complex' experiment

struct Foo {
    var numbers = [0,0,0]
    subscript(index: Int) -> Int {
        get {
            return numbers[index]
        }
        set {
            print(numbers[index],newValue)
            numbers[index] = newValue
            print(numbers[index])
        }
    }
}


var fooA:Foo! = Foo()

fooA[1] = 1
fooA[1]                  // 0
// but prints
// 0 1
// 1

for more 'fun'

var fooA:Foo! = Foo()
if var foo = fooA {
    foo[1] = 1
    print(foo)
}

prints

"Foo(numbers: [0, 1, 0])\n"


来源:https://stackoverflow.com/questions/34050677/subscript-of-a-struct-doesnt-set-values-when-created-as-an-implicitly-unwrapped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!