当结构的下标创建为隐式解包的可选内容时,不设置值 [英] Subscript of a struct doesn't set values when created as an implicitly unwrapped optional

查看:87
本文介绍了当结构的下标创建为隐式解包的可选内容时,不设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当"Foo"是一个隐式展开的可选内容时,为什么不能使用下标更改"numbers"数组?

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

由于某种原因,当我将"Foo"设置为类(以下称为"Goo")时,它会起作用

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

推荐答案

它看起来像个错误(或者我错过了一些重要的事情),请检查

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

更多复杂"实验

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

获得更多的乐趣"

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

打印

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

这篇关于当结构的下标创建为隐式解包的可选内容时,不设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆