In Kotlin we have a list of standard (scope) functions (e.g. let
, apply
, run
, etc)
Example of usage below
val str : String? = "123"
str?.let{ print(it) }
This makes the code looks more succinct without need to have if (str != null)
In swift, I code it as below
let str: String? = "123"
if str != nil { print(str!) }
I have to have if str != nil
. Is there a let
provided by default that I could use (without me writing my own)?
FYI, I'm new to Swift, and check around doesn't seems to find it.
The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called scope functions.
Both kotlin vs swift languages are built on top of the modern programming approach and software design pattern. Both the languages offer several inbuilt functions defined in an extensive list of libraries.
There are several functions in the Kotlin standard library that help in the execution of a block of code within the context of an object. Calling these functions on an object with lambda expression creates a temporary scope.
run () the code. Most other scope function kotlin does have is a mix of apply () and let function. Let’s look at below example: we use run () whenever we want to perform some operation on the object but the result is not the same object itself, but the return type of that operation is something else.
if you like if, extend the functionality of Optional
extension Optional {
func `let`(do: (Wrapped)->()) {
guard let v = self else { return }
`do`(v)
}
}
var str: String? = "text"
str.let {
print( $0 ) // prints `text`
}
str = nil
str.let {
print( $0 ) // not executed if str == nil
}
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