How would you call an Objective-C category method like this in Swift?
+(UIColor*)colorWithHexString:(NSString*)hex alpha:(float)alpha;
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With