2

I'm new to Swift sorry if this might seem too simple. But I could not find answer from anywhere.

I am trying to understand this syntax below. The code have = then {..}() why need () at the end and also = sign for ?

var productLines: [ProductLine] = { return ProductLine.productLines() }()

I understand that computed variable would be something like .. this below

var varA: [arrayOutput] { return someArray }

what exactly is ={ return something }() called or mean in swift ?

3
  • 4
    { ... } is a closure (an inline function definition). () calls that function`. Commented Mar 8, 2016 at 15:30
  • 1
    What this does, is setting the variable productLines initially with the result of the closure { return ProductLine.productLines() } The () calls that closure function. So the value of productLines can be overwritten later. So no, this is not a computed property. Commented Mar 8, 2016 at 15:32
  • 1
    apeth.com/swiftBook/ch02.html#SECdefineandcall Commented Mar 8, 2016 at 15:35

1 Answer 1

10

What you see there is a closure for setting the initial value of the variable. A closure can be described as an anonymous code block.

This is what your code looks like:

var productLines: [ProductLine] = { return ProductLine.productLines() }()

Let me expand your code like this:

var productLines: [ProductLine] = { () -> [ProductLine] in 
    return ProductLine.productLines() 
}()

The closure itself consists of the following code

{ () -> [ProductLine] in 
    return ProductLine.productLines() 
}

The two round brackets () are used to execute the closure. So what you see is not a computed property. You are therefore able to change the value of productLines like this afterwards:

productLines = [ProductLine]()

If it was a computed property instead, you would get an error like this one:

Cannot assign to property: productLines is a get-only property

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much This is exactly what I need.
Excellent answer. (Voted). I was gearing up to write an explanation, but you covered all the bases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.