W3cschool -Swift tutorial, Swift keywords in detail

Keywords related to declarations

  • class: Declares a class, or class method
class Person: Func run() {print("run")} class {print("work")}}Copy the code
  • struct: declare structure, can declare member variables, member methods. So more like a class, a lightweight implementation of a class, so to speak
Struct Person {var name:String var age:Int func rule (){print(" I am: \(name), year \(age) ")}} // declaration: struct Person {var name:String var age:Int func rule (){print(" I am: \(name), year \(age) ")}} Var person = person (name: "xiaoMing",age: 20) person.introduce(Copy the code
structandclassTo compare
Struct is a structure, class is a class 1, struct is a value type, class is a reference type; Declare a new variable to refer to the structure, change a property, the original structure property does not change; And the class will change along with ' Struct myStru {var width = 200} class myClass {var width = 200} var stu = myStru() var stu2 = stu stu2.width =  300 print(stu.width,stu2.width) //200 300 var cls = myClass() var cls2 = cls cls2.width = 300 Print (cls.width,cls2.width) //300 300 ' Struct class = struct class = struct class = struct class = struct class = struct class = struct class = struct class = struct class = struct class = struct class 6. All structs have an automatically generated member constructor, whereas a class needs to generate itself. 7. But in class, if a member variable has no initial value, you must write a constructor for itCopy the code
  • static: declares a static variable or function that is guaranteed to have only one copy of the corresponding scope and does not rely on instantiation. If used to modify a function, represents a class method and cannot be overridden
Class Person: NSObject {var name: String // class method, and this method cannot be overridden by subclasses static func run() {print(self.name + "running")}}Copy the code
staticandclassTo compare
Are used to specify class methods before 'func', except that class methods that are 'static' cannot be overriddenCopy the code
  • typealias: Aliases for all types
// declare typeAlias ABC = Int // call let a: ABC = 100Copy the code
  • enumEnumeration, a common data type. Benefits: Using enumerations prevents users from using invalid values, and the variable makes the code clearer.
// write 1, 0, 1, 2, 3 enum Orientation1:Int{case East case South case West case North} // Syntax 2 enum Orientation2:Int{case East,South,West,North} // Call the specific value print(Orientation1.East.rawValue,Orientation1.South.rawValue,Orientation2.West.rawValue,Orientation2.North.rawValue) // Prints 0, 1, 2, 3Copy the code
  • extension: expansion, similar to occategoryCategorization, but more powerful than categorization. Generally used:
    1. Adding computed Attributes
    2. Add methods
    3. Add an initialization method
    4. Add subordinate scripts, such as subscripts
    5. Add and use nested types
    6. Follow and implement a protocol
// Add a run method to the person class: NSObject {var name = "swift"} extension Person{func run() {print(self.name + "running")}} per.run()Copy the code
  • subscript: subscript script, can makeThe structure of the body,The enumeration,classUse the subscript function. Note:subscriptYou can have nosetMethod, but have itgetmethods
struct Person {
    var age = 0
    var no  = 0
    subscript(index: Int) -> Int {
        set {
            if index == 0 {
                age = newValue
            } else {
                no = newValue
            }
        }
        get {
            if index == 0 {
                return age
            } else {
                return no
            }
        }
    }
}

var p = Person()
p[0] = 10
p[1] = 20

print(p.age)  // 10
print(p[0])   // 10

print(p.no)  // 20
print(p[1])  // 20
Copy the code

Example of passing multiple arguments:

Class Matix {var data = [[0,0,0], [0,0,0]] subscript(row: Int, col: Int) -> Int {set {// guard, Return guard row >= 0 && row < 3 && col >= 0 && col < 3 else {return} data[row][col] = newValue} get { Guard row >= 0 && row < 3 && col >= 0 && col < 3 else {return 0} return data[row][col]}} // call var m = Matix() m[1, 1] = 3 m = 4 [0, 1] / / the beyond the scope of direct return the m (4, 4) = 9 print (m. ata) / / print [[0, 4, 0], [0, 3, 0], [0, 0, 0]]Copy the code
  • init: constructor, initialization method
Class PerSon: NSObject {// If you do not assign an initial value to the property directly, you must declare the constructor var name:String init(name: String) {self.name = name}} // call let person = person.init (name: Let per = person (name: "xiaoHong") print(per.name)Copy the code
  • Deinit: destructor, release method. As with DEALloc in OC, used for: object destruction, KVO removal, notification removal, NSTimer destruction

  • Protocol: the agreement

Key words related to statements

  • fallthrough: Penetrating: In the switch, execute the current case and proceed to the next case
Switch num {case 100: fallthrough case 200: print("100 + 200") default: Print ("no")} switch num {case 100,200: print("100 + 200") default: print("no")}Copy the code
  • where: for screening conditions, applicable todo-catch,switch,for-in,The generic,agreementEtc.
For I in array where I > 40 {print(I)} // Print 100 45Copy the code

Keywords related to expressions and types

  • isThe type checking operator that checks whether an instance belongs to a specific subclass and returns true, not false
Let array: [Any] = [12, "zhangsan"] // 2. Let objcFirst = array.first! If objcFirst is Int {print(" Int ")} else {print(" non-int ")}Copy the code
  • as: type conversion operator that converts up from a derived class to a base class
// The value itself is defined as an int, Var number = 1 as float print(number) //1.0 var number = 1 as floatCopy the code
  • as! : Downward conversion to its subclass type. It is a forced conversion. If the conversion fails, an error will be reported

  • as? : Rules and as! Again, if the conversion fails, a nil object is returned

Let array: [Any] = [12, "zhangsan"] // 2. Let objcLast = array.last! // 3. Convert to the real type to use // as? Let name = objcLast as? String print(name) // Result :Optional("zhangsan") // as! Set Any to a specific type, otherwise the program will crash let name2 = objcLast as! String print(name2) // Result :zhangsanCopy the code

Keywords in a particular context

  • 9. The convenience constructor modifies the init constructor, usually used to extend the init constructor of a system class.

    1. convenienceUsually written in the bookextensionIn the
    2. Need to be ininitBefore you addconvenience
    3. inconvenienceNeeds to be explicitly calledself.init()
*/ required convenience public init(...) */ required convenience public init(...) {... self.init() ... }Copy the code
  • required: is used to modify classes onlyinitInitialization method, indicating that the initialization method must be implemented. Subclasses are required to implement the parent class’s initialization methods

Rules of Use:

  1. Can only be used to modify class initialization methods
  2. If the parameters of a subclass initialization method are different from those of the parent class, implement the parent class firstrequired initMethod, cannot be used at this timeoverrideUse it the same wayrequiredmodified
  3. If a subclass doesn’t have an init method, it doesn’t have to implement the parent classrequired initmethods
Class PerSon: NSObject {var name: String} class PerSon: NSObject {var name: String} String) { self.name = name } } class Student: PerSon { var age: Int = 0 required init(name:String) {super.init(name: name)} String, age:Int) { self.age = age super.init(name: firstName) } }Copy the code
  • mutating: In a structure or enumeration, before func, to indicate that the instance and instance attributes of which it belongs can be modified. Use to modify the value of a member variable in an internal member method
Struct myStruct1 {var num1 = 100 var num2 = 200 var num3 = 300} var stu1 = myStruct1() print(stu1.num1)// Stu1.num1 = 99 print(stu1.num1) struct myStruct2 {var num1 = 100 var num2 = 200 var num3; stu1.num1 = 99 print(stu1.num1) struct myStruct2 {var num1 = 100 var num2 = 200 var num3 Var stu2 = myStruct2() print(stu2.num1)//100 ChangeNum (mark: 99) print(stu2.num1)// print(stu2.num1)Copy the code
  • lazy: lazy loading, embellishing variables, and initializing values only on the first call
lazy var first = NSArray(objects: "1","2")
Copy the code
  • Override: Overrides the method of the parent class

  • Final: can be used to modify class, func, var, to indicate that cannot be overridden. You can protect a class or part of its implementation from subclass destruction

  • Inout: Objects of value type are passed by reference, meaning that external variables can be modified

Func test(num: &a) print(a)//11 func test(num: &a) print(a)//11Copy the code
  • deferDeferred execution, which modifies any code in a function so that it must be invoked before the other code in the function has finished executing and the function is about to end. If there are more than onedeferIt’s going to be executed bottom-up
Func test(){print(" defer1") defer{print(" defer2")} defer{print(" defer2")} defer{print(" defer3") }} // call test() // print the start function to end defer3Copy the code

Adding asynchronous threads

Func test () {print (" function ") defer {print (" executive defer1 ")} defer {print (" executive defer2 ")} DispatchQueue. Main. AsyncAfter (deadline: .now()+1) {print(" defer ")} print(" function will end ") defer{print(" defer ")}} test() Defer3 execute Defer2 execute defer1 end of asynchronous execution Conclusion: The asynchronous code does not affect the execution time of defer. In fact, the execution of defer depends only on the scope it is in, and if the scope is about to be reclaimed, defer will be executed before it is reclaimed.Copy the code
  • throws: After the functions that may have exceptions or errors, the errors will be brought out, and the errors will be handled during the call, saving maintenance costs; Usually when called will cooperatetry,do-catchUsed together

Code examples:

Enumeration enum MyError: Error {case ErrorOne case ErrorTwo case ErrorOther} // Use: thisFuncCouldThrowError Int) throws -> String{if type == 1 {return "success"}else if type == 2{throw myerror. ErrorTwo}else{throw Myerror.errorother}} // with do catch to catch exceptions, Do {let stu = try thisFuncCouldThrowError(20) print(" ") print(stu)} catch let err as MyError/* */{print(" error ") print(err)} catch {// There must be an empty catch. The reason is that} // may have been omitted with the error ErrorOther printedCopy the code
  • rethrows: The keyword passed upward by an exception is not the function or method itself, but the closure type parameter it carries. When throwing its closure type parameter throws, we use rethrows to continue passing the exception upward until it is used by the caller. This provides one more pass session than throws
Throws func thisFuncCouldThrowError(_ type: Int) throws -> String{if type == 1 {return "success"}else if type == 2{throw myerror. ErrorTwo}else{throw MyError.ErrorOther } } //rethrows func thisFuncRethrows(_ throwsError:(Int) throws -> String) rethrows{ do { let stu = Try throwsError(20) print(" ") print(stu)} catch let err as MyError{throw err} catch{}} let afunc = Self. ThisFuncCouldThrowError do {try self. ThisFuncRethrows (afunc) print (" there is no error, if there is an error, ")}catch let err as MyError {print(" error ") print(err)}catch{// There must be an empty catch or an error is reported. The reason is possible omission}Copy the code

Five, access permission keywords

Swift provides five access control permissions: Private, Fileprivate, internal, public, and Open

  • private: is accessible only in the current class, in the extension modified class, but not in subclasses and other classes
  • fileprivate: Can be accessed only in the current source file. That means subclasses in different files are also inaccessible
  • internal: Default access level. The entire module can be accessed in the source code
  • public: can be accessed by anyone. It can be override and inherited in this module, but not in other modules
  • open: can be used by anyone, including Override and inheritance