swift 4.0中 private的变化

很庆幸时隔不久发现之前有关于侮辱程序猿的文章都删除了,然而还是被这个平台伤害过,掘金的整个环境也确实比好很多,然而真的有点放不下之前写的文章。也记得开始写文章时,它的每一次点击和感谢都会让我欣喜。所以我会把想写的东西也在发布。但是... 还是去掘金玩去啦! 但是两边会同步更新!!!

之前在swift 3.0的时候,如果把声明的变量或方法加上private前缀,那么它就只能在当前的class里使用,extension 中也不能使用。改成fileprivate,却又可以在其他类中实例化后使用,属性的作用域就会更大,可能会不小心造成属性的滥用。

所以在Swift 4 中,private 的属性的作用域扩大到了 extension 中,并且被限定在了 struct 和 extension 内部,这样就不需要再改成 fileprivate 了。

上代码

class ViewController: UIViewController {

    var test = ""
    private var test1 = ""
    fileprivate var test2 = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        testIt() // 之前会报错 需要修改为fileprivate
    }

    func testForNormal(){
        
    }
    
    private func testForPrivate(){
        
        
    }
    
    fileprivate func testForfileprivate(){
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

extension ViewController {
    
    private func testIt(){

        testForPrivate() /// swift 4.0 可以访问  之前不行
    }
    
}

class other {
    
    let a = ViewController()
    func lalal(){
        _ = a.test /// Normal
        _ = a.test2 /// fileprivate
        a.testForNormal() /// Normal
        a.testForfileprivate() /// fileprivate
        a.testForPrivate() /// 报错 'testForPrivate' is inaccessible due to 'private' protection level
    }
    
}

你可能感兴趣的:(swift 4.0中 private的变化)