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

310
Views
¿Swift tiene funciones estándar (alcance) como en Kotlin?

En Kotlin tenemos una lista de funciones estándar (alcance) (por ejemplo, let , apply , run , etc.)

Ejemplo de uso a continuación

 val str : String? = "123" str?.let{ print(it) }

Esto hace que el código se vea más sucinto sin necesidad de tener if (str != null)

En Swift, lo codifico como se muestra a continuación.

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

Tengo que tener if str != nil . ¿Hay un let provisto por defecto que podría usar (sin que yo escriba el mío)?

FYI, soy nuevo en Swift, y parece que buscar no lo encuentra.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

si lo desea, extienda la funcionalidad de Opcional

 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

Podrías usar Optional.map :

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

imprime 123 .

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

No imprime nada.

Entonces, si un opcional no es nil , se desenvuelve y se usa como parámetro para el cierre del map . si no, no se llamará al cierre.


Un enfoque más idiomático en Swift sería usar un enlace opcional:

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

0

Aparentemente, la forma rápida de hacer la verificación de cero

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

Y si realmente quiere asegurarse de que no sea nulo, use guard (gracias @CouchDeveloper por señalarlo)

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

Sé que esto no respondió explícitamente a la pregunta de tener una función de alcance o no, pero me brinda mi intención original de encontrar la forma Swift de verificar nil o non nil que estaba buscando let como el uso de Kotlin.

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!