【问题标题】:Subscript of a struct doesn't set values when created as an implicitly unwrapped optional结构的下标在创建为隐式展开的可选时不设置值
【发布时间】:2015-12-02 18:51:12
【问题描述】:

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

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”)时它会起作用

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

【问题讨论】:

  • 当你明确解开变量时,它会起作用:`fooA![1] = 1`。但在声明任何隐式展开的可选变量之前,请考虑使用非可选的惰性初始化:var fooA : Foo = { return Foo() }()
  • 确实如此。但是为什么不显式解包变量就不能工作呢?
  • 我不知道,这就是我写评论而不是答案的原因 ;-)
  • @vadian 这就是麻烦。变量 i: 整数!!! = 10; print(i) // 10 ?????????它看起来真的,真的很奇怪!但是......它有效(原因不明)
  • mutating set 替换下标中的set 有什么不同吗?

标签: swift class struct swift2 optional


【解决方案1】:

它看起来像一个错误(或者我错过了一些重要的东西),检查一下

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"

【讨论】:

  • 假设你是对的,我将在哪里以及如何报告 swift 错误?
  • 如果你有开发者账号,在苹果雷达上做
  • 至少 fooA?[1] 应该被识别为无效表达式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
  • 1970-01-01
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
相关资源
最近更新 更多