Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

302
Views
Does swift have standard (scope) functions like in 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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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
}
over 4 years ago · Santiago Trujillo Report

0

You could use Optional.map :

let str1 : String? = "123"
str1.map { print($0) }

prints 123.

let str2 : String? = nil
str2.map { print($0) }

Doesn't print anything.

So if an optional is not nil, it is unwrapped and used as a parameter to the map closure. if not, the closure won't be called.


A more idiomatic approach in swift would be to use optional binding :

var str: String? = "123"
if let s = str { 
    print(s) 
}
over 4 years ago · Santiago Trujillo Report

0

Apparently the Swift way of doing the nil check

let str: String? = "123"
if let strUnwrapped = str { print(strUnwrapped) }

And if really want to ensure it is not nil, use guard (thanks @CouchDeveloper for pointing out)

let str: String? = "123"
guard let strUnwrapped = str else { return }

I know this didn't explicitly answer the question of having scoping function or not, but it provides me my original intent of finding the Swift way of checking nil or non nil I was looking for like the let of Kotlin being used.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!