Home Imperative Vs Declarative Programming in Swift
Post
Cancel

Imperative Vs Declarative Programming in Swift

When SwiftUI came out, I start hearing about that it’s declarative, even if you went to the SwiftUI website you will find that they are saying one of the SwiftUI features that it has a declarative syntax.

So, What is actually declarative syntax? and what is the imperative syntax?

As easy as that…

I’ll give you a real-life example and I’m sure it will make it easy for you to understand. Imagine that you will ask someone to buy you a bottle of water from the supermarket.

Imperative way:

Stand up, walk until you reach the door, open the door, exit the office, take the lift, exit the building, enter the supermarket, buy the bottle of water.

Declarative way:

Please buy a bottle of water for me.

As you can see, the imperative approach is about HOW he will get you water, while the declarative approach is about WHAT you want!.

Keep this in your mind, imperative is HOW, declarative is WHAT.

Enough metaphors, more code.

I’ll show you the same function but with imperative implementation first the declarative implementation.

Imperative implementation:

1
2
3
4
5
6
7
8
9
func filter(array: [Person], name: String) -> [Person] {
  var result = [Person]()
  for item in array {
    if item.name == name {
      result.append(item)
    }
  }
  return result
}

Declarative implementation:

1
2
3
func filter(array: [Person], name: String) -> [Person] {
  return array.filter({ $0.name == name })
}

As you can see in the declarative implementation we don’t care how the filter is done we are just asking the higher order function to give us all persons with a specific name, while in the imperative way, we have an array, we go through it we check if each item name equal the name then append that item to the array if true else ignore it.

Same defiance between SwiftUI and UIKit, look at this table view example.

SwiftUI:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct ContentView: View {
  var persons: [Person] = [
    Person(name: "abed"),
    Person(name: "you")
  ]
  var body: some View {
    List(persons) { person in
      Text(person.name)
      .font(.subheadline)
      .foregroundColor(.gray)
    }
  }
}

UIKit:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class ContentViewController: UIViewController, UITableViewDataSource {
  private var tableView: UITableView!
  var persons: [Person] = [
    Person(name: "abed"),
    Person(name: "you")
  ]
  override func viewDidLoad() {
    super.viewDidLoad()
    setupTableView()
  }
  private func setupTableView() {
    tableView = UITableView()
    tableView.dataSource = self
    tableView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(tableView)
  
    let topAndBottomMargens = CGFloat(16)
    NSLayoutConstraint.activate([
      tableView.topAnchor.constraint(equalTo: view.bottomAnchor, constant: topAndBottomMargens),
      tableView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
    ])
  }
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return persons.count
  }
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let personCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PersonTableViewCell
    personCell.textLabel?.textColor = .gray
    personCell.textLabel?.text = persons[indexPath.row].name
    return personCell
  }
}

In the UIKit example, we are telling UIKit how to create everything and this makes the code longer and harder to be understood.

-❤️~.
If you have any questions you can send me a message on Twitter or facebook. Also you can check my Github page or my Apps.

This post is licensed under CC BY 4.0 by the author.