swift扩展中的类函数(类别)

ale*_*nca 14 ios swift

是否可以在swift中的扩展中定义类函数,就像在Objective-C类中一样,您还可以定义类函数?

objective-c中的示例

@implementation UIColor (Additions)

+ (UIColor)colorWithHexString:(NSString *)hexString
{
    // create color from string
    // ... some code
    return newColor;
}

@end
Run Code Online (Sandbox Code Playgroud)

swift中的等价物是什么?

Kir*_*ins 23

是的,它可能和非常相似,主要的区别是Swift扩展没有命名.

extension UIColor {
    class func colorWithHexString(hexString: String) -> UIColor {
        // create color from string
        // ... some code
        return newColor
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 自定义初始化程序可能是更快的解决方案,因为这是Objectice-C工厂方法映射到的. (4认同)

ale*_*nca 6

作为记录.以下是上述解决方案的代码:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我可以使用:

迅速:

let clr:UIColor = UIColor(hexString:"000000")
Run Code Online (Sandbox Code Playgroud)

理论上我应该能够在objective-c中使用:

UIColor *clr = [UIColor colorWithHexString:@"000000"];
Run Code Online (Sandbox Code Playgroud)