gpt4 book ai didi

arrays - Swift - 使用范围运算符将项目添加到数组,奇怪的行为

转载 作者:搜寻专家 更新时间:2023-11-01 06:41:15 25 4
gpt4 key购买 nike

在 swift playground 中,这段代码工作正常:

shoppingList = ["item0", "item1", "item2", "item3"]
shoppingList[3...3] = ["item4", "item5", "item6"]
shoppingList.count // prints 6.
shoppingList // prints item0 through item6 (minus item3) in the shoppingList.

但是如果我们REPLACE下面四行中的每一行,上面的第二行,不会产生编译错误,但是shoppingList.count不会打印出任何东西:

shoppingList[3...4] = ["item4", "item5", "item6"] // Doesn't Work!
shoppingList[3...6] = ["item4", "item5", "item6"] // Doesn't Work!
shoppingList[4...6] = ["item4", "item5", "item6"] // Doesn't Work!
shoppingList[3...5] = ["item4", "item5", "item6"] // Doesn't Work!

在我看来,如果出于某种原因 shoppingList[3...3] = ["item4", "item5", "item6"] 正在作为数组的 append 工作,这对我来说似乎是合乎逻辑的,至少上面三行中的一行应该可以正常工作。

最佳答案

全部

shoppingList[3...4] = ["item4", "item5", "item6"] // Doesn't Work!
shoppingList[3...6] = ["item4", "item5", "item6"] // Doesn't Work!
shoppingList[4...6] = ["item4", "item5", "item6"] // Doesn't Work!
shoppingList[3...5] = ["item4", "item5", "item6"] // Doesn't Work!

导致fatal error: Array index out of range因为4不是包含 4 个元素的数组的有效索引。

如果您想使用下标 setter 追加到数组(“拼接”)然后你可以使用 ..< 排除上限的范围运算符:

var shoppingList = ["item0", "item1", "item2", "item3"]

shoppingList[4 ..< 4] = ["item4", "item5", "item6"]
// ["item0", "item1", "item2", "item3", "item4", "item5", "item6"]

当然,+=appendContentsOf()也可以使用。

关于arrays - Swift - 使用范围运算符将项目添加到数组,奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987307/

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