Swift_访问控制(open>public>fileprivate>insternal>private)

ViewController.swift


//基类
//不加 private 私有修饰符,默认class类是公开的
class Test: UIViewController {
    
    
    
    //1、private 私有,只能在当前类访问
    private var  private_value:Int?
    private func private_func(){}

    
    
    //2.1、默认访问级别
    //如果你不为代码中的实体显式指定访问级别,那么它们默认为 internal 级别(有一些例外情况,稍后会进行说明)。因此,在大多数情况下,我们不需要显式指定实体的访问级别。
    var hide_internal_var:Int? = 0
    func hide_internal_func(){}

    
    
    
    //2.2、internal 显式内部成员级别,通过继承来访问
    internal var internal_var:Double?
    internal func internal_func(){}
    
    
    
    //3、fileprivate 当前类文件可访问
    fileprivate var fileprivate_var:Int?
    fileprivate func fileprivate_func(){}

    
    
    //4、public 公开
    public  var  public_var:Double?
    public func public_func(){}
    
    
    
    
    //5、open 可以被任何人使用,包括override和继承。
    open var  open_var:Int?
    open func open_func(){}

}


//子类
class SubTest: Test {

    var value:Any?
    
    //5、
    override func open_func() {
        super.open_func()
        value = super.open_var
    }
    func useOpen(){
        
        let sub_open_var = super.open_var
    }
    
    
    //4、
    override func public_func() {
        super.public_func()
        value = super.public_var
    }
    func usePublic(){
        value = super.public_var
    }

    
    //3、
    fileprivate override func fileprivate_func() {
        value = super.fileprivate_var
        super.fileprivate_func()
    }
    func useFilePrivate(){
        value = super.fileprivate_var
    }
    
    
    //2.2、
    override func internal_func() {
        
    }
    func useInternal(){
        value = super.internal_func()
    }
    
    
    //2.1、
    override func hide_internal_func() {
        
    }
    func useHideInternal(){
        value = super.hide_internal_var
    }
    
    
    //1、私有函数和变量无法被子类获取  Expected decLaration
    //super.private_value
    //super.private_func()
    
}


class anyClass:Test {
    
    
}





class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        var testClass = Test()
        let a = testClass.fileprivate_var
        
        
    }


    

}



AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        var testClass = Test()
        let a = testClass.fileprivate_var
        return true
    }






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值