Is there a pretty way to increment an optional Int?

非 Y 不嫁゛ 提交于 2020-01-03 07:18:11

问题


I want to increment an Int?
Currently I have written this :

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

Is there some prettier way to write this ?


回答1:


For the sake of completeness, Optional has a map() method:

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

Therefore

index != nil ? index! + 1 : nil

is equivalent to

index.map { $0 + 1 }



回答2:


You can call the advanced(by:) function using optional chaining:

return index?.advancedBy(1)

Note: This works for any Int, not just 1.


If you find yourself doing this many times in your code, you could define your own + operator that adds an Int to an Int?:

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

Then you could just do:

return index + 1



回答3:


You can optionally call any method on an optional by prepending the call with a question mark, and this works for postfix operators too:

return index?++

More generally you can also write:

index? += 1; return index


来源:https://stackoverflow.com/questions/33804794/is-there-a-pretty-way-to-increment-an-optional-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!