I have a model class which keeps, amongst other things, the user’s current location.

public class WorldModel : NSObject, CLLocationManagerDelegate {
    private var latitude : Double = 0.0
    private var longitude : Double = 0.0
    ...
}

While the location is used for internal calculations, there is also a screen where I display the current location to the user. Formatting the two values for display is easy enough, but non-trivial and worth encapsulating. I found the simplest way to encapsulate it was by creating a computed property on the model class itself.

    var latLonString : String {
        get {
            let vizLatitude = Double(abs(Int32(latitude * 100))) / 100
            let vizLongitude = Double(abs(Int32(longitude * 100))) / 100
            let latitudeDirection = latitude < 0 ? "S" : "N"
            let longitudeDirection = longitude < 0 ? "W" : "E"
            return "\(vizLatitude)\(latitudeDirection), \(vizLongitude)\(longitudeDirection)"
        }
    }

The first two lines inside the get method truncate to two decimal places, then I figure out the North, South, East, West bits and finally return a formatted string.

Now displaying the current latitude and longitude to the user is a simple task by referring to the new property.

currentLocation.text = myWorldModel.latLonString

While a string representation of complex data is quite common, you can go the other way, too. The same class has a property for a current hue (think red, yellow, green, turquoise, blue, pink) stored as a Double, and a complex function to determine the display brightness based on the sun’s position (thus needing your location). So… what colour should the interface use right now? Easy!

    var currentHue = 0.0
    var currentColour : UIColor {
        get {
            return UIColor(hue: CGFloat(currentHue), saturation: 1.0, brightness: CGFloat(0.5 + lightLevel() / 2), alpha: 1.0)
        }
    }

The currentColour computed property automatically passes me a UIColor object using the current hue and the brightness based on, ultimately, the user’s location and local time (and thus sun position).

Once again, using the computed property is simple.

let currentColour = myWorldModel.currentColour
doneButton.setTitleColor(currentColour, forState: UIControlState.Normal)
currentLocationLabel.textColor = currentColour
currentLocation.textColor = currentColour
...

Any time you want to make use of values that can always be derived from stored properties, consider creating a computed property to do the work.

Comment