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 ?
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.
No, it's not as efficient. As you can see from the reference implementation it has to store, update and check an extra value.
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.
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
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 }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With