gpt4 book ai didi

swift - 可选的可变力展开,我还没有看到解决方案

转载 作者:行者123 更新时间:2023-11-28 12:24:56 24 4
gpt4 key购买 nike

强制展开是邪恶的,所以我尽可能地使用 guard 或 if let,但有时这真的让我很头疼。

函数中基于 1 的列表索引变量到基于 0 的数组

//index is an integer from a 1 based list, so it can be 1, 2, 3,... (index is coming from an external API)
func someFunction (index : Int?) {
guard let newIndex = index - 1 else {
throw Abort.custom(status: .badRequest,
message: "blah blah")
}
let result = myArray[newIndex]
....
}

编辑器标记错误"

Value of optional type Int is not unwrapped, did you mean to use ! or ?"

行中的@index:guard let newIndex = index - 1 else {

添加一个!索引导致另一个错误:

"Initializer for conditional binding must have Optional type, not int"

所以我目前使用的解决方案是:

 guard var newIndex = index else {
throw Abort.custom(status: .badRequest,
message: "blah blah")
}

newIndex -= 1
let result = myArray[newIndex]
....

它有效,但我认为它的编码有点丑陋......

最佳答案

您可以使用方法调用而不是运算符进行减法:

func someFunction (index : Int?) {
guard var newIndex = index?.advanced(by: -1) else {
throw Abort.custom(status: .badRequest,
message: "blah blah")
}

let result = myArray[newIndex]
....
}

这并不能笼统地回答问题,而是针对您的具体情况。

关于swift - 可选的可变力展开,我还没有看到解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43682699/

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