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?

2
  • Wouldn't we always use functions as class functions, as long as we don't use instance variables/computed properties? Commented May 15, 2015 at 12:52
  • See this SO answer for a description of how to create Swift extensions. Commented Jun 24, 2015 at 12:49

2 Answers 2

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

A custom initializer might be the swiftier solution, since that is what Objectice-C factory methods are mapped to.
That's what I'll do now. Thanks for the suggestion.
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"];

1 Comment

Also a note that you can make init fail-able when invalid hexString is provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.