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 ?
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 ?
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 }
+1
and that it would work with any other number :) –
Florencia 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 }
+1
and that it would work with any other number :) –
Florencia 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
return index? += 1
doesn't work. It gives compile error error: cannot convert return expression of type '()?' to return type 'Int?'
–
Vicky © 2022 - 2024 — McMap. All rights reserved.