JPC
JPC

Reputation: 5173

swift syntax using var ={}() meaning?

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 ?

Upvotes: 2

Views: 203

Answers (1)

Sebastian Krogull
Sebastian Krogull

Reputation: 1528

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

Upvotes: 10

Related Questions