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?
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.
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.
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. }
Yes, you can extend a final class.
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
}
}
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"];
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