Singleton with Swift 3.0

前端 未结 6 1672
灰色年华
灰色年华 2021-01-15 04:33

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

6条回答
  •  鱼传尺愫
    2021-01-15 05:03

    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.

提交回复
热议问题