12

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 ?

vacawama
  • 150,663
  • 30
  • 266
  • 294
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134

3 Answers3

9

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
vacawama
  • 150,663
  • 30
  • 266
  • 294
8

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 }
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2

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
Tom Pelaia
  • 1,275
  • 10
  • 9
  • 1
    As said in an deleted question, this has the downside to not working when index is a constant (let) – Matthieu Riegler Nov 19 '15 at 16:13
  • `return index? += 1` doesn't work. It gives compile error `error: cannot convert return expression of type '()?' to return type 'Int?'` – vacawama Nov 19 '15 at 22:56
  • You are correct. I have edited my code snippet to fix the problem. Anyway, it still doesn't meet the requirement of working with let and there is already a good answer using map. – Tom Pelaia Nov 20 '15 at 13:23