Swift5.1学习随笔之访问控制Access Control

2020-05-14  本文已影响0人  SAW_

在访问权限控制中,swift中提供了5个不同的访问级别(以下是从高到低排列,实体指被访问级别修饰的内容)

open class Person { }

public class Person { }

internal class Person { }

fileprivate class Person { }

fileprivate class Person {
    private var age: Int = 0
}

访问级别的使用准则

一个实体不可以被更低访问级别的实体定义,比如
fileprivate class Person { }
internal var person: Person // Variable cannot be declared internal because its type uses a fileprivate type
class Person { }
public typealias MyPerson = Person // Type alias cannot be declared public because its underlying type uses an internal type
fileprivate typealias MyInt = Int
fileprivate typealias MyString = String

public enum Score {
    case point(MyInt) // Enum case in a public enum uses a fileprivate type
    case grade(MyString) // Enum case in a public enum uses a fileprivate type
}

元组类型

元组类型的访问级别是所有成员类型最低的那个

internal struct Dog {}
fileprivate class Person {}

//(Dog, Person)的访问级别是fileprivate
fileprivate var data1: (Dog, Person)
private var data2: (Dog, Person)

泛型类型

泛型类型的访问级别是类型的访问级别以及所有泛型类型参数的访问级别中最低的那个

internal class Car {}
fileprivate class Dog {}
public class Person<T1, T2> {}

//Person<Car, Dog>()的访问级别是fileprivate
fileprivate var p = Person<Car, Dog>()

成员、嵌套类型

类型的访问级别会影响成员(属性、方法、初始化器、下标)、嵌套类型的默认访问级别

fileprivate class Person {
    var age = 0 //默认fileprivate
    func fun() { } //默认fileprivate
    enum Season { case spring, summer } //默认fileprivate
}

getter、setter

fileprivate(set) public var num = 10
class Person {
    private(set) var age = 0
    fileprivate(set) public var weight: Int {
        set {}
        get { 10 }
    }
    internal(set) public subscript(index: Int) -> Int {
        set {}
        get { index }
    }
}

var p = Person()
p.age = 10 // Cannot assign to property: 'age' setter is inaccessible
print(p.age) // 可以访问

初始化器


枚举类型的case

不能给enum的每个case单独设置访问级别

enum Season {
    internal case spring // 'internal' modifier cannot be applied to this declaration
    case summer
}

协议

协议中定义的要求自动接收协议的访问级别,不能单独设置访问级别
public协议定义的要求也是public

protocol Runnable {
    private func run() // 'private' modifier cannot be used in protocols
}

扩展

class Person { }
fileprivate extension Person {
    func run() { } // 默认 fileprivate
}
class Person { }
extension Person {
    func run() { } // 默认跟在Person里面基本一样
}
class Person { }
extension Person {
    private func run() { }
}
protocol Runnable { }
class Person { }
//'fileprivate' modifier cannot be used with extensions that declare protocol conformances
fileprivate extension Person: Runnable {
    func run() { }
}
public class Person {
    private func run0() {}
    private func eat0() {
        run1()
    }
}

extension Person {
    private func run1() {}
    private func eat1() {
        run0()
    }
}

extension Person {
    private func eat2() {
        run1()
    }
}
上一篇 下一篇

猜你喜欢

热点阅读