What is a good example to differentiate between fileprivate and private in Swift3

前端 未结 10 1114
醉梦人生
醉梦人生 2020-11-27 10:03

This article has been helpful in understanding the new access specifiers in Swift 3. It also gives some examples of different usages of fileprivate

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 10:23

    Updated for Swift 5

    Private vs FilePrivate

    For better clarity paste the code snippet in Playground

    class Sum1 {
        let a: Int!
        let b: Int!
        private var result: Int?
        fileprivate var resultt: Int?
    
        init(a : Int, b: Int) {
            self.a = a
            self.b = b
        }
    
        func sum(){
            result = a + b
            print(result as! Int)
        }
    }
    
    let aObj = Sum1.init(a: 10, b: 20)
    aObj.sum()
    aObj.resultt //File Private Accessible as inside same swift file
    aObj.result //Private varaible will not be accessible outside its definition except extensions
    
    extension Sum1{
    
        func testing() {
    
            // Both private and fileprivate accessible in extensions
            print(result)
            print(resultt)
        }
    }
    
    //If SUM2 class is created in same file as Sum1 ---
    class Sum2{
    
        func test(){
    
            let aSum1 = Sum1.init(a: 2, b: 2)
            // Only file private accessible
            aSum1.resultt
    
        }
    }
    

    Note: Outside of Swift file both private and fileprivate are not accessible.

提交回复
热议问题