extension

  • To the existingstruct,enum,classTo add new features
  • Extensions cannot override existing functionality
  • Computational attribute
    extension Int {
        var add: Int {
            return self + 100
        }
    }
    let addition = 3.add
    Copy the code
  • Constructor and method
    struct sum { var num1 = 100, Num2 = 200} extension sum {// add func updateTemp() {// add mutating func update() {self.num1 = 300} extension sum {// add func update() {self Add a new constructor init(x: Int, y: Int) {self.num1 = x self.num2 = y}Copy the code
  • Nested types
    extension Int {
        enum calc {
            case add
            case sub
        }
        var print: calc {
            switch self {
            case 0:
                return .add
            case 1:
                return .sub
            default:
                return .add
            }
        }
    }
    
    print(3.print)
    Copy the code

protocol

  • A protocol specifies the methods and attributes necessary to implement a particular function
  • protocolMust specifygetandset, used by the read-only attribute{get}
    enum days { case sun,mon,tue } protocol daysOfWeak { var mark: Int {get set} var result: Bool {get} // In the method, change the value type instance mutating func show()}Copy the code
  • required: guarantees that all subclasses that follow the protocol also provide a realistic implementation or inherited implementation of the constructor
    protocol tcpProtocol { init(no: Int) } class mainClass { var no: Int init(no: Int) { self.no = no } } class subClass: mainClass,tcpProtocol { var no2: Int init(no: Int, no2: Int) { self.no2 = no super.init(no: Override required Override convenience init(no: Int) {self.init(no: no, no2: none) {override required override convenience init(no: no, no2: 2)}}Copy the code
  • protocolCan be used as a type
  • inextensionIn the implementationprotocol
    protocol tcpProtocol {
        func ageType() -> String
    }
    class mainClass {
    
    }
    extension mainClass: tcpProtocol {
        func ageType() -> String {
            return ""
        }
    }
    Copy the code
  • Protocols can inherit from one or more protocols
  • classExclusive agreement
    • throughclassKeyword, the restriction protocol can only be applied toclassType in the
    • classKeyword that must appear first in the inheritance list of the protocol
    protocol tcpProtocol: class {
    	func ageType() -> String
    }
    Copy the code
  • Agreement synthesis
    • .and&Delimiter when following multiple protocols
      protocol Stname { var name: String {get} } protocol Stage { var age: Int {get} } struct Person: Stname, Stage {var name: String var age: Int} // Celebrator follows both Stage and Stname func show(celebrator: Stage & Stname) { print("\(celebrator.age) + \(celebrator.name)") }Copy the code
  • Check that protocols are followed
    • as?
    Let per = Person(name: "1", age: 0) // Check whether the instance complies with a protocol. If per is Stage {print("per confirm to Stage")} // Return nil if the protocol is followed, otherwise return nil if let obj = per as? Stage { print("per confirm to Stage") }Copy the code

The generic

  • Generics use placeholder type names (<T>) instead of the actual type to avoid repetitive code writing
  • The function name is followed by the placeholder type name(T)And enclose them in Angle brackets<T>
  • <T>Angle brackets inswifttheTIs the placeholder type name of the function definition,swiftIt doesn’t look for namesTThe actual type name of the
    func swapTwoValues<T>(_ a: inout T, _ b: inout T) { let temp = a a = b b = temp } var num = "123" var num2 = "78" swapTwoValues(&num2, &num) print("\(num) + \(num2)"Copy the code
  • Define a generic stack
    struct Stack<T> { var items = [T]() mutating func push(_ item: T) {items.append(item)} mutating func pop() -> T {return items.removelast ()}} // A list of type parameters declared in the original type definition  Stack { var topItem: T? { return items.isEmpty ? nil : items[items.count - 1] } }Copy the code
  • Type constraints
    • Specifies a type parameter that must inherit from the specified class or follow a specific protocol
    func findIndex<T: SomeClass, U: SomeClass>(index: T, array: U) {
    
    }
    Copy the code
  • associatedtype
    • Association types use keywordsassociatedtypeTo define the
      protocol Container { associatedtype ItemType mutating func append(_ item: ItemType) var count: Int { get } subscript(i: Int) -> ItemType { get } } struct Stack<T>: Container { typealias ItemType = T var items = [T]() mutating func push(_ item: T) {items.append(item)} mutating func pop() -> T {return items.removelast () append(_ item: T) { self.push(item) } var count: Int { return items.count } subscript(i: Int) -> T { return items[i] } }Copy the code
    • In the parameter list, passwhereAttach constraints that define parameters
      Func allItemMatch<C: Container, C2: Container>(_ someC: C, _ anotherC: C2) -> Bool where C.ItemType == C2.ItemType, C.ItemType: Equatable { if someC.count ! = anotherC.count { return false } for i in 0.. <someC.count { if someC[i] ! = anotherC[i] { return false } } return true }Copy the code

Access control

  • public
  • open
    • Can only be modifiedclass, has the highest access permission
    • Can be inherited in the current module as well as in imported modules
    • Can be overridden in the current module as well as in the imported module
  • internal
    • Default access restrictions
    • Entities in the module source file cannot be accessed by others
  • fileprivate
    • Access is available within the current file
  • private
    • Can only be accessed in the current class, not out of scope
  • Access rights such as subclasses and properties
    • A subclass cannot have more access than its parent class
    • Attribute, constant, and subscript access permissions cannot exceed those of this class
    • The necessary constructors must have the same level of access as this class
    • Protocol access
    Public protocol Container {associatedType ItemType} public mutating func append(_ item: ItemType)}Copy the code
    • A type alias has less access than or equal to its original type