Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a pretty way to increment an optional Int?

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 ?

like image 778
Matthieu Riegler Avatar asked Nov 19 '15 13:11

Matthieu Riegler


People also ask

How to increment integer with a variable in java?

There are two ways to use the increment operator; prefix and postfix increment. The prefix increment looks like ++variablename; while the postfix increment looks like variablename++; . Both of these operations add one to the value in the variable.

How efficient is std :: optional?

No, it's not as efficient. As you can see from the reference implementation it has to store, update and check an extra value.

How do you increment a variable in Swift?

Swift provides an increment operator ++ and a decrement operator to increase or decrease the value of a numeric variable by 1. The operator with variables of any integer or floating-point type is used. The ++ and -- symbol is used as a prefix operator or postfix operator.


3 Answers

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
like image 57
vacawama Avatar answered Nov 10 '22 04:11

vacawama


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 }
like image 37
Martin R Avatar answered Nov 10 '22 04:11

Martin R


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
like image 27
Tom Pelaia Avatar answered Nov 10 '22 04:11

Tom Pelaia