“This is the 13th day of my participation in the November Gwen Challenge. See details: The Last Gwen Challenge 2021”.

I was often told that it was easy to write SWIFT with OC, but I found in the process of continuous learning that the actual situation was not like that. If I did write in that way, I would only write SWIFT with OC type instead of applying real SWIFT skills. I personally think there should be some of these techniques, and they will be updated over time. Here are some of the techniques I actually use:

Manage some global constants in a single file:

When we need to create some globally generic constants to manage the project, we should create a file and manage all constants only there.

Enum AppConstants {static let AppName = "AppName" static let AppVersion = "1.0.0"... }Copy the code

Multiple layers use guard lets instead of nested if lets

Using the if example, you can see that the nesting goes on and on. If there are fewer if levels, it’s ok. If there are more if levels, the organization will be messy after a period of time, and it will be combed all over again.

let a:String? = ""

   let b:String? = ""

   if let tempa = a {
      if let tempb = b {
         print(tempa,tempb)
      }
   }
Copy the code

While using guard lets is literal, multiple guard lets just keep going down. Always be clear.

    let a:String? = ""
    let b:String? = ""
    
    guard let tempa = a else { return  }
    guard let tempb = b else { return  }
    ...
    print(tempa,tempb)
Copy the code

Use where skillfully

In the past, we used to write:

if let path = webUrl { if path.hasPrefix("https") { //... }}Copy the code

Use the WHERE keyword instead

If let path = webUrl, path.hasprefix (" HTTPS ") {// do good}Copy the code

Where is more useful for checking whether the association type must identify a protocol that falls after the WHERE keyword, which is covered in more detail in a later keyword series. This is where.

Weak Custom delegate:

This prevents circular references.

protocol P1 : AnyObject {}

class Class1 {
    weak var delegate : P1?
}
Copy the code

Use extensions to subdivide

The obvious way to subdivide with an extension is UITableView.

extension UITableView: UITableViewDataSource{
    ...
}

extension UITableView: UITableViewDelegate {
    ....
}
Copy the code

Using a generic

The good use of generics has left us with a lot of repetitive code. Generics allow you to declare a variable that, when executed, can be assigned to a set of types that we define.

func printObjc<T> (_ obj: T, message: String = "") { 
     print("\(message)\(obj)") 
}
Copy the code

Omit using KVO

KVO (Key Value Observer), where you can set and observe any Key and action when the Value of the Key changes. It’s a good swift approach, but not a better one. There is an alternative to KVO in Swift, the Property Observer. We use it to get the action when the value of the property is about to change. WillSet is called before storing a value,didSet is called immediately after storing a new value.

class Class1 {
      var num: Int = 0 {
      willSet(newValue) {
         print("newValue = \(newValue), oldValue = \(num)")
      }
      
      didSet {
         print("oldValue = \(oldValue), currentValue = \( num)")
      }
   }
}
Copy the code

Use Defer wisely

Defer is a block that stands for instructions that you want to execute later. It can contain one line of code or a bunch of lines of code. We can define a defer block in the function that will be called at the end of the function execution. It also reduces code redundancy.

func checkdefer() {

        defer {
           print("1")
        }

        print("2")
    }
Copy the code

Using defer allows you to ensure that some actions (such as resource release) must take place before the function completes. Memory free).

Use nested functions wisely

You can define a function using the body of another function, called a nested function. Nested functions are hidden from the outside world, but can be called and used by their enclosing functions. Closed functions can also return nested functions so that they can be used in the outside world or elsewhere. I think it makes sense to improve code readability and reusability, but infinite nesting is also a headache.

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backwards ? stepBackward : stepForward
}
Copy the code

Use Playground for some simple tests

Playground is a very simple and interactive Swift tool. Tests that test some logical code can be validated on Playground and also used to learn on Playground. For a basic introduction to playground, check out the official help documentation.