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. Calls with labels take far 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; even the shorthand ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access