Appendix B. Some Useful Utility Functions

As you work with iOS and Swift, you’ll develop a personal library of frequently used convenience functions. Here are some of mine. Each of them has come in handy in my own life; I keep them available in Xcode’s Snippets library, so that I can use them in any project. Many of them have been mentioned earlier in this book.

Core Graphics Initializers

The Core Graphics CGRectMake function needs no argument labels when you call it. But Swift cuts off access to this function; instead, you’re forced to use various CGRect initializers that do need argument labels. I don’t like that. Calls with labels take longer to enter into your code, and the labels are superfluous because we know what each argument signifies. My solution is a CGRect initializer without labels (Chapter 1):

extension CGRect {
    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {
        self.init(x:x, y:y, width:w, height:h)
    }
}

As long as we’re doing that, we may as well supply label-free initializers for the other common Core Graphics structs:

extension CGSize {
    init(_ width:CGFloat, _ height:CGFloat) {
        self.init(width:width, height:height)
    }
}
extension CGPoint {
    init(_ x:CGFloat, _ y:CGFloat) {
        self.init(x:x, y:y)
    }
}
extension CGVector {
    init (_ dx:CGFloat, _ dy:CGFloat) {
        self.init(dx:dx, dy:dy)
    }
}

The examples throughout this book, including the rest of this appendix, rely on those extensions.

Center of a CGRect

One frequently wants the center point of a CGRect; it’s ...

Get Programming iOS 14 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.