如何使同一类的对象成为初始化程序的返回值?

时间:2018-02-09 03:13:28

标签: swift convenience-methods

我有这个功能:

extension UIImage {

    static func from(layer: CALayer) -> UIImage? {
        UIGraphicsBeginImageContext(layer.frame.size)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let outputImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return outputImage
    }

}

如何将其更改为这样?

extension UIImage {

    convenience init(layer: CALayer) {
        self.init();
        UIGraphicsBeginImageContext(layer.frame.size)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let outputImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self = outputImage; // Error: cannot assign to self: self is immutable
    }

}

我希望UIGraphicsGetImageFromCurrentImageContext()的结果成为启动的“自我”。但结果已经是UIImage。我不认为我应该在这个函数中使用“变异”吗?

1 个答案:

答案 0 :(得分:4)

由于错误状态UIImage是不可变的。您可以做的是从outputImage获取CGImage并使用UIImage init(cgImage: CGImage) initializer从中初始化新图片:

extension UIImage {
    convenience init?(layer: CALayer) {
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0)
        defer { UIGraphicsEndImageContext() }
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }
        layer.render(in: context)
        guard let outputImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
            return nil
        }
        self.init(cgImage: outputImage)
    }
}