【问题标题】:Is there a pretty way to increment an optional Int?有没有一种很好的方法来增加一个可选的 Int?
【发布时间】:2016-02-21 15:34:17
【问题描述】:

我想增加一个Int?
目前我已经写了这个:

return index != nil ? index!+1 : nil

有没有更漂亮的方法来写这个?

【问题讨论】:

  • 不,简单的数学运算符不适用于可选项。

标签: swift int increment optional


【解决方案1】:

您可以使用可选链接调用advanced(by:)函数:

return index?.advancedBy(1)

注意:这适用于任何Int,而不仅仅是1


如果您发现自己在代码中多次这样做,您可以定义自己的 + 运算符,将 Int 添加到 Int?

func +(i: Int?, j: Int) -> Int? {
    return i == nil ? i : i! + j
}

那么你可以这样做:

return index + 1

【讨论】:

  • 您的回答很好!
【解决方案2】:

您可以通过在调用前加上问号来选择性地调用可选的任何方法,这也适用于后缀运算符:

return index?++

更一般的你也可以写成:

index? += 1; return index

【讨论】:

  • 正如在一个已删除的问题中所说,当索引为常量 (let) 时,这会导致无法正常工作
  • return index? += 1 不起作用。它给出了编译错误error: cannot convert return expression of type '()?' to return type 'Int?'
  • 你是对的。我已经编辑了我的代码 sn-p 来解决这个问题。无论如何,它仍然不符合使用 let 的要求,并且使用 map 已经有一个很好的答案。
【解决方案3】:

为了完整起见,Optional 有一个map() 方法:

/// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
@warn_unused_result
@rethrows public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?

因此

index != nil ? index! + 1 : nil

等价于

index.map { $0 + 1 }

【讨论】:

  • 我喜欢 +1 的增量更明显,并且它适用于任何其他数字:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 2022-10-23
相关资源
最近更新 更多