Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

304
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda