gpt4 book ai didi

swift - 结构的下标在创建为隐式展开的可选时不设置值

转载 作者:搜寻专家 更新时间:2023-10-31 23:01:31 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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 - 结构的下标在创建为隐式展开的可选时不设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34050677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com