Jay Q.
Jay Q.

Reputation: 4999

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;

Upvotes: 7

Views: 7446

Answers (1)

rickster
rickster

Reputation: 126167

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)
}

Upvotes: 16

Related Questions