15

Is it possible to define a class function in an extension in swift, just like in an objective-C category you can also define class functions?

Example in objective-c

@implementation UIColor (Additions)

+ (UIColor)colorWithHexString:(NSString *)hexString
{
    // create color from string
    // ... some code
    return newColor;
}

@end

what would be the equivalent in swift?

alex da franca
  • 1,450
  • 2
  • 15
  • 27
  • Wouldn't we always use functions as class functions, as long as we don't use instance variables/computed properties? – brainray May 15 '15 at 12:52
  • See [this SO answer](http://stackoverflow.com/a/31026358/3681880) for a description of how to create Swift extensions. – Suragch Jun 24 '15 at 12:49

2 Answers2

24

Yes, it possible and very similar, the main difference is that Swift extensions are not named.

extension UIColor {
    class func colorWithHexString(hexString: String) -> UIColor {
        // create color from string
        // ... some code
        return newColor
    }
}
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
6

For the record. Here's the code for above's solution:

import UIKit

extension UIColor {
    convenience init(hexString:String) {

        // some code to parse the hex string
        let red = 0.0
        let green = 0.0
        let blue = 0.0
        let alpha = 1.0

        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }
}

Now I can use:

swift:

let clr:UIColor = UIColor(hexString:"000000")

and theoretically I should be able to use in objective-c:

UIColor *clr = [UIColor colorWithHexString:@"000000"];
alex da franca
  • 1,450
  • 2
  • 15
  • 27