Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 727
Jay Q. Avatar asked Jun 03 '14 02:06

Jay Q.


1 Answers

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
NS_SWIFT_NAME(init(hexString:));
@end

// imports as
extension UIColor {
    init(hexString: String)
}
like image 96
rickster Avatar answered Oct 01 '22 19:10

rickster