There isn't something like that in Swift, so we need to find a way to write a takeIf
function ourselves.
In Kotlin, takeIf
is available on everything, as an extension function on all T
:
inline fun <T> T.takeIf(predicate: (T) -> Boolean): T?
In Swift, you can't write an extension on Any
, so we can only make a global function:
func take<T>(_ value: T, if predicate: (T) throws -> Bool) rethrows -> T? {
try predicate(value) ? value : nil
}
// example usage:
let x = Int.random(in: 0..<10)
let y = take(x, if: { $0 > 5 })
If you are creative enough to think of an operator, you can turn this into an infix operator, similar to how the Kotlin takeIf
is in between the receiver and the predicate.
// I am not creative enough...
infix operator ???
func ???<T>(value: T, predicate: (T) throws -> Bool) rethrows -> T? {
try predicate(value) ? value : nil
}
let a = Int.random(in: 0..<10)
let b = x ??? { $0 > 5 }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…