Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class function in swift extension (category)

Tags:

ios

swift

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?

like image 984
alex da franca Avatar asked Dec 08 '14 12:12

alex da franca


People also ask

What is a class extension Swift?

Swift Class Extensions Another way to add new functionality to a Swift class is to use an extension. Extensions can be used to add features such as methods, initializers, computed properties and subscripts to an existing class without the need to create and reference a subclass.

What is the difference between category VS extension in Swift?

Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.

How do I create a class extension in Swift?

Creating an extension in Swift Creating extensions is similar to creating named types in Swift. When creating an extension, you add the word extension before the name. extension SomeNamedType { // Extending SomeNamedType, and adding new // functionality to it. }

Can we create extension of final class in Swift?

Yes, you can extend a final class.


2 Answers

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
    }
}
like image 138
Kirsteins Avatar answered Oct 04 '22 22:10

Kirsteins


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"];
like image 25
alex da franca Avatar answered Oct 05 '22 00:10

alex da franca