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

 林寿辉 发布于 2022-12-07 12:47

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

objective-c中的示例

@implementation UIColor (Additions)

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

@end

swift中的等价物是什么?

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"];
    

    2022-12-11 02:14 回答
  • 是的,它可能和非常相似,主要的区别是Swift扩展没有命名.

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

    2022-12-11 03:09 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有