Jay Q. Jay Q. - 1 year ago 101
Objective-C Question

How to call an Objective-C category method in Swift

How would you call an Objective-C category method like this in Swift?

+(UIColor*)colorWithHexString:(NSString*)hex alpha:(float)alpha;

Answer Source

The compiler automatically looks for common ObjC naming patterns and substitutes Swift patterns in their place. An ObjC class method that returns an instance of the class (and is named a certain way, it looks like) gets turned into a Swift convenience initializer.

If you have the ObjC method (defined by a custom category):

 + (UIColor *)colorWithHexString:(NSString *)hex alpha:(float)alpha;

The compiler generates the Swift declaration:

convenience init(hexString: String?, alpha: CFloat)

And you call it like this:

let color = UIColor(hexString: "#ffffff", alpha: 1.0)

And in Swift 2.0 or later, you can use the NS_SWIFT_NAME macro to make ObjC factory methods that don't match the naming pattern import to Swift as initializers. e.g.:

@interface UIColor(Hex)
+ (UIColor *)hexColorWithString:(NSString *)string

// imports as
extension UIColor {
    init(hexString: String)