View Code

Hello, Devs!

On the last years with my team, were are using Storyboards.

From now on we get started with View Code.

I was writing the and learning the best way to do that and I have some doubts around it.

In particular case I writing something like that (Is not done from while)

import UIKit



Code Block
class TopView: UIView {
  
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupTopView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupTopView() {
        self.addSubview(contentTopView )
    }
    let contentTopView: UIView = {
        let topView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
        topView.backgroundColor = .gray
        topView.layer.cornerRadius = 12
        topView.layer.shadowRadius = 1.0
        topView.layer.shadowOpacity = 0.5
        topView.layer.shadowColor = UIColor.lightGray.cgColor
        topView.layer.shadowOffset = CGSize(width: 0, height: 10) 
        
        return topView
    }()
}



This is the best way to write View Code? Why I should to use () on the final block of the contentToTopView after the }?

Thanks,
Cheers!!!


Accepted Answer
The () at the end causes the closure to execute and thus to return a view as the result.

If you skip it, you don't get a view, but a clossure that can create a view.

It is like defining a func:

Code Block
func aFunc() {
print("I'm a func")
}
let b = aFunc
print("b is", b)
b() // you get the print.


You get
b is (Function)
I'm a func

View Code
 
 
Q