An story of how Apple change the way we code for iOS

1 min read

Image
Photo by Nikolaos Dimou: source

Around 2019, Apple introduces SwiftUI, a new way to code for Apple devices, making it so easy and fast to build interfaces without compromising the effort learning about constraints and the interface builder used for UIKit.

What kind of changes, you tell?

Well, in SwiftUI taking example of the button, now you can code it and see a preview of it in mere seconds

Example:

struct ExampleView: View {
    var body: some View {
        VStack {
            Button("Submit SwiftUI", action: {}})
        }
        .padding()
    }
}

and the preview looks like this: Image

in the UIKit side: Image

The ViewController will look like this:

Tip

Don't forget to add the reference of the button of the storyboard It won't work without it

import UIKit

class HelloViewController: UIViewController {

    @IBOutlet weak var submitButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        submitButton.addTarget(
        self, 
        action: #selector(submitHelloWorld), 
        for: .touchUpInside
        )
    }
    
    @objc func submitHelloWorld() {
        print("Hello World!")
    }
    
}

Classic implementation and kinda messy if we make some updates to the reference...

what about the SwiftUI one?

Well, if you looked carefully at the code with SwiftUI, the component Button has a parameter called action, so we can pass a function there :)

struct ExampleView: View {
    var body: some View {
        VStack {
            Button("Submit SwiftUI", action: submit)
        }
        .padding()
    }
    
    private func submit() {
        print("Hello World!")
    }
}

OK