This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021


The introduction

When I started to write Swift code, it was always not concise and did not give full play to the characteristics of Swift. As the writing went on, I also summarized some Swift development tips to make the code look more concise and elegant.

Content is divided into two articles, we first look at the first ~


Using built-in functions

Now we have an array of integers, and we want to add up all the numbers in the array. Your first reaction might be a for loop, so you write the following code:

let numbers = [2021.11.12]
var sum = 0
for number in numbers {
    sum + = number
}
print(sum)    / / 2044
Copy the code

There’s nothing wrong with this, of course, but we can use reduce(_:_:) to simplify the for loop to a single line:

let numbers = [2021.11.12]
let sum = numbers.reduce(0.+)
print(sum)   / / 2044
Copy the code

This is equivalent to 0 + 2021 + 11 + 12 reduce. The first argument, 0, is the initial value, which is equivalent to var sum = 0 in the for loop above. The second argument accepts a closure, which gives us the opportunity to do whatever we want inside the closure.

In addition to reduce(_:_:), Swift provides other built-in functions such as filter(_:), map(_:), flatMap(_:), firstIndex(Where :), and more. Command + Shift +0 opens the development document for more information.


Omit the return keyword

If a function or closure has only one line of code, you can omit the return keyword. And, if you prefer, you can put all the code on one line:

func makeGreeting(withName name: String) -> String {
    "Ask for a thumbs up,\(name)"
}

func makeGreeting(withName name: String) -> String { "Ask for a thumbs up,\(name)" }
Copy the code

Simplify the closure

struct Person {
    var name: String
    var age: Int
    .
}
Copy the code

Select Persons older than 18 from Persons array filter(_:);

let person1 = Person(name: "JieJie", age: 20)
let person2 = Person(name: "Faker", age: 25)
let person3 = Person(name: "JakeyLove", age: 30)
let person4 = Person(name: "JinX", age: 10)
let persons = [person1, person2, person3, person4]

let result = persons.filter { person in
    person.age > 18
}
print(result.map{ $0.name }) //["JieJie", "Faker", "JakeyLove"]
Copy the code

Swift automatically provides parameter name abbreviations for inline functions, so the above filter statement can be simplified to:

let result = persons.filter{ $0.age > 18 }
Copy the code

Check if the array is out of bounds

If you draw persons and the number of persons is not 6, extend the drawing date, you might do this:

let index = 6
if index > = 0 && index < persons.count {
    print("Congratulations\(persons[index].name)The winning")}else {
    print("Extension of Lucky Draw Date")}Copy the code

The indices property for arrays is used to make it bigger:

if persons.indices.contains(index) {
    print("Congratulations\(persons[index].name)The winning")}else {
    print("Extension of Lucky Draw Date")}Copy the code

The default value

Everyone knows you can use?? Set defaults for optional variables. In Swift, there are more places to set defaults, such as:

  • Set default values for function parameters
  • Set a default value for a key in the dictionary

Let’s start by setting the default value for a function parameter, which can be omitted when called:

func greet(name: String = "World") -> String { 
    "Hello,\(name)" 
}

greet("World!!!")  //Hello,World!!!

greet()   //Hello,World
Copy the code

Let’s look at setting a default value for a key in a Dictionary.

Suppose we have a Names array that contains names of people, and now we write a function that returns the names that occur the most. One way to do this is as follows:

let names = ["Zhang"."Xiao li"."Zhang"."Xiao li"."Zhang"."Wang"]

func findMostCountName(inNames names: [String]) -> String {
    var occurrenceFor: [String : Int] = [:]
    for name in names {
        if let count = occurrenceFor[name] {
            occurrenceFor[name] = count + 1
        } else {
            occurrenceFor[name] = 1}}var maxCount = 0
    var result = ""
    for (name, count) in occurrenceFor {
        if count > maxCount {
            maxCount = count
            result = name
        }
    }
    return result
}

let name = findMostCountName(inNames: names)
print(name) / / zhang
Copy the code

Let’s look at the default value for dictionary: occurrenceFor’s key:

func findMostCountName(inNames names: [String]) -> String {
    var occurrenceFor: [String : Int] = [:]
    for name in names {
        occurrenceFor[name, default: 0] + = 1  // If the key exists, return the corresponding value; Otherwise return 0
    }
    
    var maxCount = 0
    var result = ""
    for (name, count) in occurrenceFor {
        if count > maxCount {
            maxCount = count
            result = name
        }
    }
    return result
}
Copy the code

As you can see, setting default values for the Dictionary key makes your code look cleaner. Replace the if-else statement with a single line of code.


Check if the variable is between two numbers

If you have a field: age, now determine if it is between 18 and 32. Here’s what we usually do:

let age = 23

if age > = 18 && age < = 32 {
    print("Fit the bill")}Copy the code

You might think there’s nothing wrong with writing like this, but look at this:

let age = 23

if age < = 18 && age > = 32 {
    print("Fit the bill")}Copy the code

Isn’t that true, but the print statement will never execute. How do you feel when you read these two if statements? Do you need to have a pause in your brain to think about whether or not you fit the criteria? This makes it unreadable and error-prone.

Swift provides a more readable and easy way to:

let age = 23

if (18.32).contains(age) {
    print("Fit the bill")}if (18.32) ~ = age {
    print("Fit the bill")}Copy the code

conclusion

  • Use built-in functions instead of for loops whenever possible
  • One-line functions omit the return keyword
  • Closure simplification
  • Check for array out-of-bounds methods
  • Provide default values for function parameters and dictionary keys
  • Check if the variable is between two numbers

That’s all for today’s tip. You might as well practice it in your project if you think it’s useful