I had this implementation with Swift 2.0 and the Xcode suggestion is not only baffling but causes compilation error as well. it\'s a library where users are passing callfunc
This works (as in it won't call callfunc
twice), if you don't mind the function becomes @escaping
:
class Main {
private static var CALLER: (() -> MyProtocol)?
private static let GETTER: MyProtocol = CALLER!()
public class func getSingleton(_ callfunc: @escaping () -> MyProtocol) -> MyProtocol {
CALLER = callfunc
return GETTER
}
}
Note that this does not address thread safety (CALLER
can be changed before reaching GETTER
), and the CALLER
will be overwritten every time getSingleton
is used which may impose some performance penalty.