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 insetBy
, 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 dw:CGFloat, dh:CGFloat) -> CGSize { return CGSizeMake(self.width ...
Get Programming iOS 9 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.