【发布时间】:2016-02-21 15:34:17
【问题描述】:
我想增加一个Int?
目前我已经写了这个:
return index != nil ? index!+1 : nil
有没有更漂亮的方法来写这个?
【问题讨论】:
-
不,简单的数学运算符不适用于可选项。
标签: swift int increment optional
我想增加一个Int?
目前我已经写了这个:
return index != nil ? index!+1 : nil
有没有更漂亮的方法来写这个?
【问题讨论】:
标签: swift int increment optional
您可以使用可选链接调用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
【讨论】:
您可以通过在调用前加上问号来选择性地调用可选的任何方法,这也适用于后缀运算符:
return index?++
更一般的你也可以写成:
index? += 1; return index
【讨论】:
return index? += 1 不起作用。它给出了编译错误error: cannot convert return expression of type '()?' to return type 'Int?'
为了完整起见,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 的增量更明显,并且它适用于任何其他数字:)