Declaring a Simple Class in Swift

By Jesse Feiler

Here, you explore the inner workings of Swift classes, structures, and enumerations (at least the inner workings that are common to all of them — refer to the table).

Features in Classes, Structures, and Enumerations
Feature Classes Structures Enumerations
Instances X X X
Properties X X computed properties only
Methods X X X
Subscripts X X X
Initializers X X X
Extensions X X X
Protocols X X X
Inheritance X
Type casting X
Deinitializers X
ARC X

In Locatapp (actually the Master-Detail Application template) you can see two views at the same time when you run the app on an iPhone 6 Plus or any of the iPad models. When held horizontally (in landscape orientation), any iPad or an iPhone 6 Plus shows two views side by side as you see in the figure.

image0.jpg

On older iPhone models, however, you have a navigation interface: One view appears at a time. You navigate from view to view but only one view is visible at all times.

In the template, most of the code is in the master view controller (this is the view at the left). It’s the view that lets you create events and delete events. The master view controller tells the detail view controller (shown at the right) the specific data to display — in fact, this is why it’s called a detail view controller.

The detail view controller is implemented with a relatively simple class called DetailViewController. The simplicity of this class is why it’s a good class to examine to get an idea of how classes work.

The listing shows the code for DetailViewController. As you can see, there’s not much code involved, so it’s easy to explore the entire class. The comments show the before and after syntax for the lines of code changed to implement the map.

Most Swift classes look like this one (except that many of them are bigger):

//
//  DetailViewController.swift
//  Locatapp
//
//  Created by Jesse Feiler on 10/23/14.
//  Copyright (c) 2014 Jesse Feiler. All rights reserved.
//
import UIKit
import MapKit
class DetailViewController: UIViewController {
  //@IBOutlet weak var detailDescriptionLabel: UILabel!
  @IBOutlet var mapView: MKMapView!
    var detailItem: AnyObject? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }
    func configureView() {
        // Update the user interface for the detail item.
        /*if let detail: AnyObject = self.detailItem {
            if let label = self.detailDescriptionLabel {
                label.text = 
detail.valueForKey("timeStamp")!.description } }*/ } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }