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

280
Visualizações
Using closures as parameters without trailing closures Swift

When using trailing closure syntax it seems quite easy to pass a function as a parameter of another function.

However I want to do this WITHOUT using the trailing closure syntax

func doSomethingTwo(closure: (String) -> Void) {
    closure("AAA")
}

doSomethingTwo(closure: print("TEST") )

gives Cannot convert value of type '()' to expected argument type '(String) -> Void'

I know that

doSomethingTwo{ (test: String) in
    print ("\(test)")
}

works, but want this without the trailing closure syntax.

This is not a homework problem, I am looking at tutorials and have done research that has not given me an answer to this question.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You need to define your own print method to pass it as a parameter:

func doSomethingTwo(closure: (String) -> ()) {
    // when you call the closure you need to pass the string to be printed
    closure("TEST")
}

Define the method to print the string that will be passed to the closure:

let closure: (String) -> () = { print($0) }

Then you can call it as you wish:

doSomethingTwo(closure: closure)
over 4 years ago · Santiago Trujillo Relatório

0

This is how you call a function

doSomethingTwo()

If we follow the pattern, put () first, then comes with its parameter, you'll get something like this.

doSomethingTwo(closure: { (str) in
     print(str)
})

By the way, Xcode will helps you to complete. But if you don't want its help, when you have this, don't tap, type the rest by your own. enter image description here

over 4 years ago · Santiago Trujillo Relatório

0

You're not calling the function correctly. You should call it like this:

doSomethingTwo(closure: { (text) in
print(text)
})
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