Vog*_*gel 5 initialization objective-c uiimage convenience-methods swift
我正在尝试做这样的事情:
public extension UIImage {
public convenience init(whatever: Int) {
UIGraphicsBeginImageContextWithOptions(...)
//...
let image = UIGraphicsGetImageFromCurrentContext()
UIGraphicsEndImageContext()
return image // <- impossible
}
}
Run Code Online (Sandbox Code Playgroud)
但这不可能,因为“nil”是初始值设定项的唯一有效返回值……我该怎么做?
例如,Objtive-C 方法 [UIImage imageNamed:] 是一个类方法(它可以在 Objective-C 中返回它想要的任何内容)并且它被映射到 swift 初始值设定项 UIImage(named:)。
您想要的是类工厂方法,而不是初始化程序。Foundation/Cocoa 中的大多数工厂方法都会自动桥接到初始化程序,但是如果无法通过 完成您想要的操作init,您可以添加一个新的类方法:
public extension UIImage {
class func imageWithWhatever(whatever: Int) -> UIImage {
UIGraphicsBeginImageContextWithOptions(...)
//...
let image = UIGraphicsGetImageFromCurrentContext()
UIGraphicsEndImageContext()
return image
}
}
Run Code Online (Sandbox Code Playgroud)