Can't use private property in extensions in another file

后端 未结 2 1203
被撕碎了的回忆
被撕碎了的回忆 2021-01-04 01:54

I can\'t use private property in extension. My extension is in another file.

How can I use private property in extension?

2条回答
  •  迷失自我
    2021-01-04 02:35

    While @nhgrif is correct about how painful is that protected is missing in Swift, There is a way around.

    Wrap your object with protocol, and declare only about the methods and properties that you wish to expose.

    For Example

    MyUtiltyClass.swift

    protocol IMyUtiltyClass {
        func doSomething()
    }
    
    class MyUtiltyClass : IMyUtiltyClass {
    
        static let shared : IMyUtiltyClass = MyUtiltyClass()
    
        /*private*/
        func doSomethingPrivately() {
    
        }
    }
    

    MyUtiltyClass+DoSomething.swift

    extension MyUtiltyClass {
        func doSomething() {
            self.doSomethingPrivately()
            print("doing something")
        }
    }
    

    And then you treat the object as the interface type and not the class/struct type directly.

    MyViewController.swift

    class MyViewController : UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            MyUtiltyClass.shared.doSomething()
            /*
             //⚠️ compiler error
             MyUtiltyClass.shared.doSomethingPrivately()
             */
        }
    }
    

    Happy Coding

提交回复
热议问题