Declarative keywords in swift

Keywords: Swift Attribute

origin

Learn swift, the keywords in swift, of course, to understand clearly. Recently, I saw articles on declaring keywords on the Internet, collate and record them.

A keyword is a sequence of reserved characters similar to an identifier and cannot be used as an identifier unless it is enclosed in accents (`).Keyword is a predefined reserved identifier that has a special meaning to the compiler.

There are four common keywords:

  • Keywords related to declarations: class, deinit, enum, extension, func, import, init, let, protocol, static, struct, subscript, typealias, and var.
  • The keywords associated with the statement: break, case, continue, default, do, else, fallthrough, if, in, for, return, switch, where, and while.
  • Expression and type keywords: as, dynamicType, is, new, super, self, self, Type, u COLUMN_, u FILE_, u FUNCTION_ and u LINE_u.
  • Keyword used in a specific context: associativity, didSet, get, infix, inout, left, mutating, none, nonmutating, operator, override, postfix, precedence, prefix, rightset, unowned, unowned(safe), unowned(unsafe), weak, and willSet.

Overview of declarative keywords

Common declaration keywords for swift are organized as follows (don't want to read long text, just look at the following figure)

Declare keyword details

1,class

In swift, we use the class keyword to declare a class or class method.

class Person: NSObject {

    
    /// add `class` key word before function, this function become a class function
    class func work(){
        print("everyone need work!")
    }
}

So we declare a Person class.

2,let

The let keyword in swift declares a constant, and we cannot modify it.(Note: Our let-modified constant is a class, and we can modify its properties)

class iOSer: Person{
    let name: String = "ningjianwen"
    var age: Int = 30
    var height: Float = 170
}

let ITWork: iOSer = iOSer()
ITWork.age = 25
print("Lao Zi wishes to be 25 years old forever")

The name of let declaration is not modifiable in iOSer class, and age&height of VaR declaration can be modified.The ITWork instance of the let keyword declaration is also immutable, but the refresh of the internal var keyword declaration is modifiable.

3,var

The var-modified variable in swift is a variable whose value can be modified.
Note: we don't use var to reference a class, and it's unnecessary.

func iOSerClassFunction(){
        let ITWork: iOSer = iOSer()
        ITWork.age = 25
        print("Lao Zi hopes forever\(ITWork.age)year")
        
        let iOS1 = ITWork
        iOS1.age = 18
        print("iOS1 age =\(iOS1.age)")
        print("ITWork age = \(ITWork.age)")
    }
    /** Print results
    Lao Zi wishes to be 25 years old forever
    iOS1 age =18
    ITWork age = 18
    */

The result shows that the iOS1 modification also affected ITWork, indicating that the two objects point to the same block of memory space.

4,struct

In Swift, we use struct keywords to declare structs. Structures in Swift are not complex. In addition to member variables, there are more member methods than C-language structs.Makes it closer to a class.You can think of struct as a lightweight implementation of a class.

struct Student {
    var name: String
    var age: Int
    
    func introduce(){
        print("My name is:\(name),This year\(age)year")
    }
}

From the code above, you can see that structs and classes have the same functionality and can define properties and methods.However, they differ in memory management, with class being a reference type and struct being a value type.
Structures in swift are syntactically similar to C or OC, but Structures in Swift must specify a type when defining member variables.

5,enum

In Swift, we use the enum keyword to declare enumerations.Enumeration is a common data type whose main function is to refer to the value of a variable with a fixed number of possibilities as a set of named constants.For example, normally there are four possible directions, east, south, West and north.We can declare four possibilities for a set of constants to refer to directions.Using enumeration prevents users from using invalid values, and the variable makes the code clearer.

enum Orientation: Int{
    case East
    case South
    case West
    case North
        
        /**
         perhaps
         enum Orientation:Int{
         case East,South,West,North
         }
         */
}

print(Orientation.East.rawValue)
/**
 Output result 0
 
 */

Note: When defining an enumeration, we must specify the type, otherwise we will get an error when using it.If the value of an enumeration type is not assigned, it will follow the default and give itself the value we want.

6,final

The final keyword can be pre-modified with class, func, var to indicate that it is not overridden and can protect a class or part of a class from subclass corruption.

class Fruit : NSObject {
    //The modifier final means that non-rewritable protects a class or part of a class from subclass destruction
    final func price(){
        //something price code here
        //...
    }
}

class Apple: Fruit {
//    Override the `final'modified price method here with an error of'Instance method overrides a'final' instance method'
//    override func price(){
//
//    }
}

7,override

In Swift, if we want to override a method or an attribute, we need to add an override keyword before the overridden variable.

class Fruit : NSObject {
    
    var sellPrice: Double = 0.0
    var name: String = "fruit"
    func info(){
        print("this fruit name is fruit")
    }
    
    //The modifier final means that non-rewritable protects a class or part of a class from subclass destruction
    final func price(){
        //something price code here
        //...
    }
}

class Apple: Fruit {
    func eat(){
        print("eat fruit")
    }
    //Override info method
    override func info() {
        print("this fruit name is \(super.name)")
    }
    //Override name property
    override var name: String{
        set{
            super.name = newValue
        }
        get{
           return super.name
        }
    }
}

8,subscript

In swift, the subscript keyword represents the subscript, which allows class, struct, and enum to access internal values using the subscript.Instead of calling the corresponding method to get or store, such as an instance of an official website:

struct Matrix {
    let rows: 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 indexIsValid(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    //Implement the `subscript'method
    subscript(row: Int, column: Int) -> Double {
        get {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

func matrixTest(){
        var matrix = Matrix(rows: 2, columns: 2)
        matrix[0, 1] = 1.5
        matrix[1, 0] = 3.2
        print("matrix == \(matrix)")
        /**
         Print results:
         matrix == Matrix(rows: 2, columns: 2, grid: [0.0, 1.5, 3.2, 0.0])
         */
    }

9,static

In swift, we use the static keyword to declare static variables or functions, which guarantees only one copy of the corresponding scope and does not rely on instantiation.
Note: (The method specified with the static keyword is a class method, which cannot be overridden by a subclass)

10,mutating

The mutating keyword refers to a variable that can be modified.Used in structure s and enumerations, although structs and enumerations can define their own methods, by default, instance methods cannot modify properties of value types.To be able to modify attribute values in an instance method, you can add the keyword mutating before the method definition.

11,typealias

Using the keyword typealias to define a type alias (typealias is equivalent to typedef in objective-c) is to rename the type to look more semantic.What people say is: give an alias.

typealias Width = Float
typealias Height = Float
func rectangularArea(width:Width, height:Height) -> Double {
            return Double(width*height)
        }

12,lazy

The lazy key modifier variable initializes the value (i.e., lazy loading) only the first time it is called.This is often used when defining attributes, so to improve program performance, we define it as lazy and load it when it's really needed.

lazy var titleLabel: UILabel = {
       var lab = UILabel()
       lab.frame = CGRect(x: 50, y: 100, width: 200, height: 20)
       lab.textAlignment = .center
       lab.font = UIFont.systemFont(ofSize: 18)
       lab.textColor = UIColor.blue
       return lab
    }()

13,init

The init keyword also represents the constructor, the initialization method, with a "?" sign after the init, indicating that the constructor can allow failures.

class PerSon {
        var name:String
        init?(name : String) {
            if name.isEmpty { return nil }
            self.name = name
        }
    }

14,required

required is used to modify the init method, indicating that it must be implemented.

class Father: NSObject {
    var name: String?
    required init(name: String) {
        self.name = name
    }
}

class Son: Father {
    required init(name: String) {
        super.init(name: name)
        self.name = name
    }
}

It is not difficult to see from the code example above that if a subclass needs to add an initialization method that is different from the parent class, it must first implement an initialization method that has been modified by the required modifier in the parent class and use the required modifier instead of override.

Notes for using required:

  1. The required modifier can only be used to modify class initialization methods.
  2. When a subclass contains an initialization method different from the parent class (the type and number of initialization method parameters are different from the parent class), the subclass must implement the required initialization method of the parent class and use the required modifier instead of override.
  3. When the subclass does not have an initialization method, you can avoid implementing the required initialization method of the parent class.

15,extension

Extension is a bit like Objective-C's category, but it's more powerful and flexible than category. It not only extends the methods of a type or structure, but also works with protocols and others to write more flexible and powerful code.It can add new features to a specific class, strut, enum, or protocol.When you do not have permission to alter the source code, you can extend the type with an extension.Extension is a bit like OC's category -- category, but slightly different is that category has a name and extension has no name.

Extensions are also commonly used in swift development and can extend the following:

    1. Define instance and type methods
    1. Add Calculated Properties and Calculate Static Properties
    1. Define Subscript
    1. Provide a new constructor
    1. Define and use new nested types
    1. Making an existing type conform to an interface
// MARK: -Add calculation properties
extension Double{
    var km: Double { return self * 1_000.0}
    var m: Double { return self}
    var cm: Double { return self / 100.0}
}


// MARK: -Add a method to person
extension Person{
    
    func run(){
        print("People have the attribute of walking")
    }
}

//Call method:
func extensionTest(){
        
        let oneInch = 25.4.km
        print("One inch is\(oneInch) meter")
        
        let njw = Person()
        njw.run()
    }
    /** Print results
    One inch is25400.0 meter
    People have the attribute of walking
    */

16,convenience

Constructors modified with convenience are called convenience constructors.Convenient constructors are often used to extend the constructor of a system's classes.
The convenience constructors are characterized as follows:

    1. Convenient constructors are usually written in extension s
    1. Convenience function init needs to be loaded before convenience function init
    1. Explicit call to self.init() is required in the convenience constructor

17,deinit

A deinit is a destructor that is automatically executed when an object ends its life cycle, such as when the function in which it resides has been called.Same as dealloc in OC.
We usually do some resource release and notification removal in the deinit function.
Listed below:

    1. Object Destroy
    1. KVO Removal
    1. Remove notifications
    1. NSTimer Destroy

18,fallthrough

In swift, fallthrough is used to execute the current case in switch-case and continue with the following case.

19,protocol

In swift, protocol also defines the protocol, similar to OC in usage.

20,open

open modifies the object representation that can be used by anyone, including override and inheritance.

21,public

In swift, public means public access, public attributes or methods of a class or class can be accessed from anywhere in a file or module.However, other modules (an App is a module, a third-party API, a third-party framework, and so on) cannot be override and inherited, but can be override and inherited within this module.

22,internal

In swift, internal represents internal access rights.That is, the properties and method descriptions with internal access are accessible within the module and beyond.The default in swift is internal access.

23,private

In swift, private represents private access.The properties or methods of a class or class decorated with privates can be accessed in the same physical file.If the physical file is exceeded, then properties and methods with privately accessible permissions cannot be accessed.

24,fileprivate

In swift, the properties or methods modified by the fileprivate access level are accessible in the current Swift source file.

The code below is a simple demonstration of internal,private,fileprivate.

///The default is internal access, accessible within the module
class ParentClass: NSObject {
    
    ///Where can this method be `override`
    func speak(){
        print("This is a talk property, subclasses can be overridden")
    }
    
    ///This method is secret, only the parent class owns it, and the child class cannot be modified
    private func secret(){
        print("It's a secret, only I know it")
    }
    
    ///It's a secret of this class, you can't see it outside
    fileprivate func localSecret(){
        print("This is the secret of this class, out of which you will not see it")
    }
}

class FirstSon: ParentClass {
    
    ///The eldest son talks
    override func speak() {
        print("I am the eldest son")
    }
//The eldest son can't change his father's secret either
//    override func secret(){
//
//    }
    
    override func localSecret() {
        print("The son told the family secret")
    }
}
//Method Calls and Printing Results
func parentClassTest(){
        
        let parent: ParentClass = ParentClass()
        parent.speak()
//        Pare.secret()//Dad's secret can't be told
//        Pare.LocalSecret ()//Secrets at home cannot be kept private
        let oldSon: FirstSon = FirstSon()
        oldSon.speak()
//        OldSon.secret//son can't tell Dad's secret
        oldSon.localSecret() //The son told the family secret
        /** Print results
         
         This is a talk property, subclasses can be overridden
         I am the eldest son
         The son told the family secret
         */
    }

Description: The five modifier access privileges sort open > public > internal > fileprivate > private.
As far as class security is concerned, the smaller the access rights, the better.

SwiftStatementDemo

Reference resources: Detailed keywords in swift

Posted by Grant Holmes on Sun, 26 May 2019 09:19:56 -0700