Is there a pretty way to increment an optional Int?
Asked Answered
F

3

13

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 ?

Florencia answered 19/11, 2015 at 13:5 Comment(1)
Nope simple math operators don't work with optionals.Florencia
L
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 }
Logography answered 19/11, 2015 at 13:12 Comment(1)
I like that the increment is more visible with the +1 and that it would work with any other number :)Florencia
V
10

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
Vicky answered 19/11, 2015 at 13:9 Comment(1)
Nice addition to your answer !Florencia
L
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 }
Logography answered 19/11, 2015 at 13:12 Comment(1)
I like that the increment is more visible with the +1 and that it would work with any other number :)Florencia
R
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
Raychel answered 19/11, 2015 at 16:4 Comment(3)
As said in an deleted question, this has the downside to not working when index is a constant (let)Florencia
return index? += 1 doesn't work. It gives compile error error: cannot convert return expression of type '()?' to return type 'Int?'Vicky
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.Raychel

© 2022 - 2024 — McMap. All rights reserved.