Extension management for Swift projects

The way that extensions are handled in Swift is lovely. If they exist in any file, they are available project-wide. Meaning you don’t need to import them into a Swift file for functional inclusion. This is great! But if you’re working on a medium to large Swift project, you may need to tweak or add functionality to an extension or two over time.

Find In Project and other avenues of searching are available within the Xcode IDE. That introduces some cognitive load and possibly causing you to lose a thought while you’re doing some menial tasks finding code.

A solution.

You can make an Extensions.swift file in your project and keepĀ all your extensions in it. Import what you need at the top of it – usually UIKit should suffice. You could use //MARK: – UIView – type browse tags in your code to break things into categories too if you needed to.

Pretty handy!

An example to get started.

//  Extensions.swift

import UIKit

//MARK: - UIColor -

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")
        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    convenience init(netHex:Int) {
        self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)


Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.