Skip to content

Instantly share code, notes, and snippets.

@haroldjose30
Last active December 7, 2024 00:08
Show Gist options
  • Select an option

  • Save haroldjose30/8bb3f01a866a32d16b7f104b6c410a14 to your computer and use it in GitHub Desktop.

Select an option

Save haroldjose30/8bb3f01a866a32d16b7f104b6c410a14 to your computer and use it in GitHub Desktop.
Swift as Kotlin
// Returns the value if the predicate evaluates to `true`; otherwise, returns `nil`.
// this function is similar from kotlin takeIf
//
// let number: Int? = 42
// let result = number.takeIf { $0 > 40 } // Output: Optional(42)
// let invalidResult = number.takeIf { $0 < 40 } // Output: nil
//
// let string: String? = "some text"
// let resultString = string.takeIf { !$0.isEmpty } // Output: Optional("some text")
// let invalidResultString = resultString.takeIf { $0.isEmpty } // Output: nil
import Foundation
public extension Optional {
func takeIf(_ predicate: (Wrapped) -> Bool) -> Wrapped? {
guard let value = self, predicate(value) else {
return nil
}
return value
}
}
public extension NSObject {
func takeIf(_ predicate: (Self) -> Bool) -> Self? {
return predicate(self) ? self : nil
}
}
public extension String {
func takeIf(_ predicate: (Self) -> Bool) -> Self? {
return predicate(self) ? self : nil
}
}
public extension Int {
func takeIf(_ predicate: (Self) -> Bool) -> Self? {
return predicate(self) ? self : nil
}
}
public extension Double {
func takeIf(_ predicate: (Self) -> Bool) -> Self? {
return predicate(self) ? self : nil
}
}
public extension Float {
func takeIf(_ predicate: (Self) -> Bool) -> Self? {
return predicate(self) ? self : nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment