O'Reilly logo

Programming iOS 8 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix B. Some Useful Utility Functions

As you work with iOS and Swift, you’ll doubtless develop a personal library of frequently used convenience functions. Here are some that have come in handy in my own life, to which I’ve referred in the course of this book.

Delayed Performance

Delayed performance is of paramount importance in iOS programming, where it is often the case that the interface must be given a moment to settle down before we proceed to the next command in a sequence. Calling dispatch_after is particularly tedious in Swift, because its strict numeric typing necessitates a lot of casting, so here’s a utility function:

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

And call it like this:

delay(0.4) {
    // do something here
}

In my world, this is far and away the most important utility function; I use it in every single app.

Center of a CGRect

One so frequently wants the center point of a CGRect that even the Swift shorthand CGPointMake(rect.midX, rect.midY) becomes tedious. You can extend CGRect to do the work for you:

extension CGRect {
    var center : CGPoint {
        return CGPointMake(self.midX, self.midY)
    }
}

Adjust a CGSize

There’s a CGRect inset (or rectByInsetting), but there’s no comparable method for changing an existing CGSize by a width delta and a height delta. Let’s make one:

extension CGSize { func sizeByDelta(#dw:CGFloat, dh:CGFloat) -> CGSize { return ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required