如何在快速便捷的初始化方法中返回自定义对象?

问题描述 投票:4回答:2

我正在尝试做这样的事情:

public extension UIImage {
    public convenience init(whatever: Int) {
        UIGraphicsBeginImageContextWithOptions(...)

        //...

        let image = UIGraphicsGetImageFromCurrentContext()
        UIGraphicsEndImageContext()

        return image // <- impossible
    }
}

但是这不可能,因为“ nil”是初始化程序的唯一有效返回值...我该怎么做?

例如,Objtive-C方法[UIImage imageNamed:]是一个类方法(可以在Objective-C中返回所需的任何内容,并且已映射到快速初始化程序UIImage(named:)。

objective-c swift uiimage initialization convenience-methods
2个回答
5
投票
您想要的是类工厂方法,而不是初始化程序。 Foundation / Cocoa中的大多数工厂方法都自动桥接到初始化程序,但是如果无法通过init完成所需的操作,则可以添加新的类方法:

public extension UIImage { class func imageWithWhatever(whatever: Int) -> UIImage { UIGraphicsBeginImageContextWithOptions(...) //... let image = UIGraphicsGetImageFromCurrentContext() UIGraphicsEndImageContext() return image } }


1
投票
这是因为您要返回一个新对象,而不是self。初始化的目的是创建对象的结构,而不是创建一个新的对象,因此,如果要将其作为方便的初始化,则需要像这样进行:

public extension UIImage { public convenience init?(whatever: Int) { defer { UIGraphicsEndImageContext() } UIGraphicsBeginImageContextWithOptions(...) //... guard let currentContext = UIGraphicsGetCurrentContext() else { return nil } guard let image = currentContext.makeImage() else { return nil } self.init(cgImage:image) } }

也许不是方便的初始化,而是要创建一个执行您所要求的类的函数:

public class func createImage(whatever: Int) -> UIImage? { defer { UIGraphicsEndImageContext() } UIGraphicsBeginImageContextWithOptions(...) //... guard let currentContext = UIGraphicsGetCurrentContext() else { return nil } guard let cgImage = currentContext.makeImage() else { return nil } let image = UIImage(cgImage: cgImage) return image }

我很抱歉,这不是100%的代码,但这基本上是要点    
© www.soinside.com 2019 - 2024. All rights reserved.