1.swift Protocol

  • Sets the optional protocol method

    • You need to comply with the NSObjectProtocol

    • The protocol needs to be @objec

    • And the way to do that is you need @Object Optional

      @objc protocol CircleDelegate:NSObjectProtocol {
          @objc optional func cirelcPrint()
      }
      Copy the code

    • Weak var delegate:CircleDelegate?

    • Call the delegate method? .cirelcPrint? (a)

  • Protocol Mutating keyword

    • Use the mutation keyword to mark a mutation that modifies a structure

    • The mutating tag is not required in a class because class master methods can usually modify class attributes

    • You can add write extion to system methods to comply with the proxy

2.switchCase

  • case let x where x.hasSuffix(“peper”): print(“li it a spicy”)

  • You can use where in a case

3. The tuples

  • Tuples can be fetched by attributes or by subscripts

    letAmutule: (min:Int, Max :Int,sum:Int) = (2,4,6)print(amutule.sum)
    print(amutule.2)
    Copy the code

4. The number of uncertain parameters of the function

  • Pass in an uncertain parameter category, evaluate and

    func sumOfnumbers(numbers:Int...) ->Int{ var sum = 0for numbe in numbers {
            sum += numbe
        }
        return sum
    }
    print("\ [sumOfnumbers (Numbers: 2,3,4,5,5))")
    Copy the code

5. The function is passed as an argument to another function

  • A function that takes an argument, a function argument that evaluates the condition, returns a bool

  • Inside the function, pass argument 1 and call the function argument

6. Function as return value

  • Function as the return value

  • When applicable, produce a variable of function type and call the variable (function) method

7.Set the mapThe use of

  • Use map to batch manipulate elements within a collection

  • Batch processing of matching elements in line with the set can also be judged, and those that do not meet the conditions are 0

  • If the type of a closure is known and is used as a callback, the parameter type and return value can be ignored. A single closure statement will return the value of its statement as the return value

  • Arguments can be referenced by their location instead of their name, which is useful in very short closures

8.Setter and gettermethods

  • The newValue in the setter is newValue

  • You can display an alias after set

9. Monitor API availability

  • Monitor API availability for iOS 10
    func textAPI() {if # Available (iOS 10, macOS 10.12,*) {// Run on iOS 10, MacOS 10. Use 12}else{// Use previous iOS, macOS API}}Copy the code

10.Swift array

  • An array of CRUD

    Var aArray = Array(repeating: 0.4, count: 3); //aArray.isEmpty //aArray.append(<#T##newElement: Double##Double#>)
    
    //aArray.insert(<#T##newElement: Double##Double#>, at: <#T##Int#>)
    
    //aArray.remove(at: <#T##Int#>)
    
    //aArray.removeLast()
    
    for (indx,value) in aArray.enumerated() {
    print("\(indx)----\(value)")}Copy the code

11. Swift string

  • CRUD of strings

    func textString(){
        var astring = "Guten Tag!"
        ifIsEmpty {// Empty string}print("\(astring[astring.startIndex])") // G
    
        print("\(astring[astring.index(before: astring.endIndex)])")   // !
    
        print("\(astring[astring.index(after: astring.startIndex)])") // u
    
        // let aindex = astring.index(astring.startIndex, offsetBy: 7);
    
        // print("\(astring[aindex])")  // a
    
        astring.insert("!", at: astring.endIndex)
    
        astring.insert(contentsOf: "there".characters, at: astring.index(before: astring.endIndex)) // prefix = astring.hasprefix (characters, at: astring.index(before: astring.endIndex))"acutnr")
    
        _ = astring.hasSuffix("!")}Copy the code

12. Paradigm

  • Practical methods:

    • Write a family of names inside Angle brackets to create a generic function or type

    • Call a function, pass in an argument of unknown type, repeat N words, return array, array red element type is the type passed

  • Using generics – Re-implement optional types

    • Defines an enumeration of optional types

    • Use assignment

  • The implementation method, qualified parameters to comply with the protocol, the type is the same

    • Compare the same elements in two arrays, true if they are the same, false if they are not

    • It is possible to calculate the return of identical elements in two collections

    • Specify requirements for the type using where after the type name

    • For example, defining a type to implement a protocol, defining that two types are the same, or defining that a class must have a particular parent.”

    • where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element

    func anyCommonElements<T:Sequence,U:Sequence>(_ lhs :T,_ rhs: U)->Bool  where T.Iterator.Element:Equatable,T.Iterator.Element == U.Iterator.Element{
        for lhsElement in lhs {
            for rhsElement in rhs {
                if lhsElement == rhsElement {
                    return true}}}return false
    }
    Copy the code

13. Set operation

  • A. ntersection(b) The intersection of sets A and B (A&B)

  • a.symmtriDifference(b) A +B – (A&B)

  • a.union(b) A+B

  • a.subtracting(b) A-(A&B)

14. Recursive enumeration

  • The enumerator is recursively preceded by the indirect keyword

    enum ArithmeticExpression {
        case number(Int)
        indirect  case addition(ArithmeticExpression,ArithmeticExpression)
        indirect case multiplication(ArithmeticExpression,ArithmeticExpression)   
    }
    Copy the code

  • Call the enumeration

    let five = ArithmeticExpression.number(5)
    let foure = ArithmeticExpression.number(4)
    let sum = ArithmeticExpression.addition(five, foure)
    let procuct = ArithmeticExpression.multiplication(sum, .number(2))
    Copy the code
  • Operations can recursively enumerate, you need functions that can recursively,

  • If it’s a pure number, return the value directly, if it’s addition, or multiplication, compute the value of the left and right algorithms, and then add and multiply

    func evaluate(_ expression:ArithmeticExpression) -> Int{
        switch expression {
            case let  .number(value):
                return value
            case let .addition(left, right):
                return  evaluate(left) + evaluate(right)
            case let .multiplication(left, right):
                return  evaluate(left) * evaluate(right)
        }
    }
    
    Copy the code

15. Swift subscriptsubscript

  • Writing:

  • Define subscripts using the subscript keyword, specifying one or more input parameters and return types

  • Unlike instance methods, subscripts can be set to read/write or read-only

    Subscript (index:Int)->Int{get{// returns an appropriate operation of type Intreturn0}set(newValue){// Perform the appropriate assignment}}Copy the code
  • Subscripts can accept any number of inputs, and these inputs can be of any type. The return value of the subscript can also be of any type. You can use variable and variable parameters for subscripts, but you can’t use input and output parameters, and you can’t set default values for parameters

  • Defines a Matrix structure representing a two-dimensional Matrix of type Double

    struct Matrix {
        letrows: Int, columns: Int var grid: [Double] init(rows: Int, columns: Int) {self.rows = rows self.columns = columns grid = Array(repeating: 0.0,count: rows * columns) } func indexIsValidForRow(row: Int, column: Int) -> Bool {returnRow >= 0 && row < rows && column >= 0 && column < columns} subscript(row: Int, column: Int) -> Double { get { assert(indexIsValidForRow(row: row, column: column),"Index out of range")
                return grid[(row * columns) + column]
            }
            set {
                assert(indexIsValidForRow(row: row, column: column), "Index out of range")
                grid[(row * columns) + column] = newValue
            }
        }
    }
    Copy the code
  • use

16. Swift destruction process

  • Destructor is useddeinitRepresents — constructor init
  • deinit {}

17. Swift access control

  • Modules and source files

    • useimportImport another module
  • Access Level Five different access levels

    • Open access/public access —– Any file, any method, any entity under the same module

    • Internal access —- Access any entity within the module, up to that point cannot be accessed from external import modules

    • File private access can only be accessed within a defined file

    • Private access restrictions can only be accessed within a defined scope

  • Open access is the highest and private access is the lowest

  • Open access applies only to class types and class members, and differs from public access as follows

  • Open access classes that can be inherited inside or outside a module, open access classes and classes with stricter access levels can only be inherited inside the module they define

  • Open access class members can be overridden within a module or by subclasses outside the module. Public access can be overridden only within the template defined.

  • Default access level Interal level

  • Single target program, is for the entire program service, the default interal.

  • Access control syntax

    • Through the open, public, internal, filepart, private, modifier, the declaration entity access level:

  • The access level of a subclass cannot be higher than that of its parent class

  • The access level of a function

18.Pch file creation

  • TARGETS -> Bulid Settings -> search prefix -> llVm-languagePrecompile Prefix HeaderSet to YES, default to NO.
  • With llVM-language setting,Prefix HeaderPCH file path