Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

345
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda