Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does swift have standard (scope) functions like in Kotlin?

Tags:

swift

kotlin

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.

like image 919
Elye Avatar asked Mar 03 '19 06:03

Elye


People also ask

What is a scope function in Kotlin?

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.

What is the difference between Kotlin and Swift programming languages?

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.

What is the scope of lambda expression in Kotlin?

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.

What is the use of run () function in Kotlin?

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.


1 Answers

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
}
like image 75
user3441734 Avatar answered Oct 23 '22 17:10

user3441734