Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

This paper also participates inProject DigginTo win the creative gift package and challenge the creative incentive money.

preface

What I like about Swift is that it is simple enough to convey as much meaning as possible in as few words as possible. Unlike Dart: sometimes I have to decide whether to use final or const.

To be more precise, Swift is simple but not simple.

Let and var

By the end of this article, you’ll have a better idea of whether to use let or var to decorate a variable when writing Swift code.

Use the let? Var?

We all know that Swift uses let to denote immutable variables and var to denote mutable variables.

But often experience can lead us into a mistake.

Let’s start with an OC example, because in the early years of writing Swift code, basically are carried over from OC logic:

- (NSString *)getNameWithSex:(BOOL)isMan {
    NSString *name;
    if (isMan) {
        name = @"season";
    }else {
        name = @"soso";
    }
    return  name;
}
Copy the code

For a simple example, if the function entry is male, the name would be season, otherwise soso.

If you think about what it would look like if YOU wrote it in Swift, you can write it this way:

func getName(isMan: Bool) -> String {
    var name: String
    
    if isMan {
        name = "season"
    }else {
        name = "soso"
    }
    return name

}

let aName = getName(isMan: true)
print(aName)
Copy the code

Print result:

season
Copy the code

It’s so simple, you say, it can’t be a problem.

Var name: String var name: String var name: String let name: String

OC (season, soso, season, season); OC (season, soso, season);

But when it actually runs, you might not expect it:

func getName(isMan: Bool) -> String {
    let name: String
    
    if isMan {
        name = "season"
    }else {
        name = "soso"
    }
    return name

}

let aName = getName(isMan: true)
print(aName)
Copy the code

Print result:

season
Copy the code

No error reported, printing normal.

Let name = isMan? “Season” : “soso”.

If and else are assigned differentlylet?

Assignment is unique. It is impossible to assign season and soso at the same time. We are misled by experience.

In fact, this assignment is common in many open source code, but we don’t think about it carefully. Here is the code I learned from reading ObjectMapper source code:

/// Convert a JSON String into an Object using NSJSONSerialization public static func parseJSONString(JSONString: String) -> Any? { let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true) if let data = data { let parsedJSON: Any? do { parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) } catch let error { print(error) parsedJSON = nil } return parsedJSON }  return nil }Copy the code

This example also contains optional types and does a do-catch assignment, also using let.

conclusion

  • Swift recommends that we use let to modify variables as much as possible, because invariant variables are always safer and more reliable than variable variables.

    When writing code, you can use let modifier on all variables, and when you find that you need var modifier, you can be sure that the compiler will give you an error.

  • When we use the for in loop and the input parameter of the function, these parameters are actually modified with let by default. If you want to make them variable, please accept them with the var modified variable first, and then do the logic processing.

Examples are as follows:

  • We usually use Guard lets for unpacking, but it is possible to use Guard var if your unpacking variable needs to be changed.

  • Experience is important, but at the same time we can’t just follow it. After all, there are so many differences between OC and Swift.

forletwithvarWelcome to discuss and throw bricks.

We’ll see you next time.