Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

Kotlin "takeIf" statement equivalent in swift?

I have this code very simple in kotlin which returns a value if a certain condition is satisfied, or null

val speed = location.speed.takeIf { it>=0 }

I'm trying to do the same in swift, but the only way I found is this:

let speed:Double?
if (location.speed>=0){
    speed = location.speed
}else{
    speed = nil
}

Is there any way more elegant?

question from:https://stackoverflow.com/questions/65842032/kotlin-takeif-statement-equivalent-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...