【问题标题】:Class function in swift extension (category)swift 扩展中的类函数(类别)
【发布时间】:2014-12-08 12:44:19
【问题描述】:

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

objective-c 中的示例

@implementation UIColor (Additions)

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

@end

swift 中的等价物是什么?

【问题讨论】:

  • 只要不使用实例变量/计算属性,我们难道不总是将函数用作类函数吗?
  • 参见this SO answer 了解如何创建 Swift 扩展。

标签: ios swift


【解决方案1】:

是的,可能而且非常相似,主要区别在于 Swift 扩展没有命名。

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

【讨论】:

  • 自定义初始化程序可能是更快捷的解决方案,因为这是 Objectice-C 工厂方法映射到的。
  • 这就是我现在要做的。感谢您的建议。
【解决方案2】:

为了记录。这是上述解决方案的代码:

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

现在我可以使用了:

迅速:

let clr:UIColor = UIColor(hexString:"000000")

理论上我应该可以在objective-c中使用:

UIColor *clr = [UIColor colorWithHexString:@"000000"];

【讨论】:

  • 另外请注意,当提供无效的hexString 时,您可以使init 失效。
猜你喜欢
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
  • 2019-06-01
  • 2019-08-21
  • 2019-03-05
  • 2011-10-31
相关资源
最近更新 更多