0

I've seen this in the book I'm reading but I don't know what it means and what it does. Is it something like a function? I've tried looking at the Swift language book by Apple but could not find the answer.

Thanks

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
CFRJ
  • 157
  • 1
  • 12
  • Swift var init with Closure ("closure" being a keyword to master if you want to use Swift). – Larme Oct 18 '17 at 09:51

2 Answers2

3

This syntax is mostly used for declaring closure in Swift.

e.g.

let something = { print("something") }
something()//prints 'something"

Here we are declaring closure named something and then calling it later.
We can declare closures with parameters also as:

let something = { (str: String) in
    print("something param: \(str)")
}

something("ok")//prints "something param: ok"

We can even declare closures with return value as:

let something = { (str: String) -> Bool in
    print("something param: \(str)")
    return true
}

let success = something("ok")//prints "something param: ok" and return true
D4ttatraya
  • 3,344
  • 1
  • 28
  • 50
  • From your examples, what is the difference between a function and a closure? – CFRJ Oct 18 '17 at 10:11
  • In Swift there's no big difference in `closure` and `func`. Have a look at [this SO post](https://stackoverflow.com/questions/24108667/what-is-the-difference-between-functions-and-closures) – D4ttatraya Oct 18 '17 at 10:13
2

Maybe you should do the swift basics first. If you want to learn more about closures you can have a look at the following side:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

AlexWoe89
  • 844
  • 1
  • 11
  • 23