Day 16 - 100 Days of Swift

2 minute read

Project 1 (part 1)

Day 16 is the beginning of the first project! The app you start working on is a pretty simple one. It has a list of photos that the user can choose from and look at. Today you set up the Xcode project, you add the photos, and set up the table view controller to display the names of all the photos.

The first step to any app is to make the Xcode project and it is the first step today as well. We started with the Single View Application template, with Swift as the language. Then we copied in all of the photos to be used in the app.

Screenshot of Xcode's new project dialog.

Next, we made a simple little function in viewDidLoad of the view controller that gets the names of all the files that start with “nssl” and saves them in an array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    var pictures: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let fm = FileManager.default
        let path = Bundle.main.resourcePath!
        let items = try! fm.contentsOfDirectory(atPath: path)

        for item in items {
            if item.hasPrefix("nssl") {
                pictures.append(item)
            }
        }
        print(pictures)
    }

Finally, we switched the default ViewController class to inherit from UITableViewController instead of UIViewController. We traded out the UIViewController in the Main.storyboard for a UITableViewController, set it as the initial view controller, set its identity as ViewController, and embedded it in a UINavigationController. We also set an identifier on the cell. Then we adopted a couple of UITableViewDataSource methods in order to display the list of filenames that we collected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
override func tableView(_ tableView: UITableView,
                        numberOfRowsInSection section: Int)
                        -> Int {
    return pictures.count
}

override func tableView(_ tableView: UITableView,
                        cellForRowAt indexPath: IndexPath)
                        -> UITableViewCell {
    let cell = tableView
    .dequeueReusableCell(withIdentifier: "PictureCell",
                         for: indexPath)
    cell.textLabel?.text = pictures[indexPath.row]

    return cell
}

You can find my version of the project on Github.

Reflections

I’m really pumped to start building some stuff with all of the Swift fundamentals that have been covered in the last few weeks. This is obviously a pretty slow start, because a lot of people going through this are not very familiar with Xcode and he took a lot of time to explain everything that was happening. I was very tempted to keep going onto tomorrow’s section of the project because it feels really unfinished right now, but I decided to put my effort into writing this blog article instead. Slow and steady wins the race.