是否可以在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)
作为记录.以下是上述解决方案的代码:
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)
归档时间: |
|
查看次数: |
17937 次 |
最近记录: |