swift installation skills: how to use map to generate arrays and write 2 lines less code than for (with demo code)

Let's start with the conclusion: map uses 3 lines of code to solve the problem of 5 lines of code in the for loop, which is equivalent to a 40% increase in efficiency

You can't learn without (I said)

  • If you don't use it, you won't be able to use it Because you don't know the usage scenario, you can't use it because you haven't learned it thoroughly

  • Today, let's talk about one of the usage scenarios of map. Instead of generating an array through a for loop, you can write 2 lines less vertically than for, and the horizontal code length will be shortened It also introduces the abbreviation syntax of map

  • Most ios programmers first learn from objective-c and then go back to swift. They use for loops to generate arrays in oc and then process arrays. Therefore, map syntax is introduced into swift, but for in is still used because of the inherent idea

The following is an oc idea to generate an array using for in:

First, take a look at the array definition type Person to be generated
The following is the definition of the Person class: generate the array Person of the Person class

import Foundation
class Person:NSObject {
    @objc var name = ""
    @objc var age = 0
    init(name:String,age:Int){
        self.name = name
        self.age = age
    }
    override var description:String  {
    return self.dictionaryWithValues(forKeys: ["name","age"]).description
    }
}

Simulate the json array passed from the online interface

    //MARK: - the following code imitates the json data read from the Internet, and then generates a model array
    var jsons :[[String:Any]] = [
        [
            "name":"Zhang San",
            "age":18
        ],
        [
            "name":"Li Si",
            "age":19
        ],
        [
            "name":"Wang Wu",
            "age":20
        ]
    ]

The traditional for in loop handles at least 5 lines of code vertically in the array

for in method 1: use subscript [] to traverse the array (the code is too long and is not recommended)

//The writing method of array for in 1 uses subscript [i] to traverse. This method makes the code grow horizontally. It is not recommended
        var persons = [Person]()
        for i in 0 ..< jsons.count{
            let person = Person(name: jsons[i]["name"] as! String, age: jsons[i]["age"] as! Int)
            persons.append(person)
        }

for in method 2: the horizontal code omits the subscript [i], which is a little shorter

        var persons = [Person]()
        for item in jsons{
            let person = Person(name: item["name"] as! String, age: item["age"] as! Int)
            persons.append(person)
        }

Use map to form an array

 map The original meaning is mapping,The function is to put the previous array or a group of elements,adopt{}Calculation inside,Convert element by element to a new array

map common writing method 1: vertical is less than for in by 2 lines of code

        let persons = jsons.map {item in
            return Person(name: item["name"] as! String, age: item["age"] as! Int)
        }

map ellipsis: use $0 and return

        let persons = jsons.map {
            Person(name: $0["name"] as! String, age: $0["age"] as! Int)
        }
  • $0 represents the variables traversed each time. The first traversal $0 represents jsons[0], the second traversal $0 represents jsons[1], and the last traversal $0 represents jsons[jsons.count -1]
  • Since there is only one line of code in {}, return can be omitted

map, a comparison summary of the number of rows omitted when generating a new array than for in:

2 lines of code are omitted vertically:

 first line:Define a new array: For example, the above:var persons = [Person]()
 Second line:Array append element:For example, the above: persons.append(person)

Horizontal code reduction:

 for in You need to define a new variable, such as the one above  for item in jsons{ }among  item As a temporary variable for each traversal
 for i in 0 ..< jsons.count Medium jsons[i]As a temporary variable for each traversal
 And in map in,Each time you traverse a temporary variable, the first is $0,If there is a second one $1
 because map It's in the closure{}If there is only one line of code,Can be omitted return

Finally, a difference between for in and map with a set of numbers as an array is attached

Here, five array elements are generated with 0,1,2,3,4

The for in method generates an array

        var persons = [Person]()
        for i in 0 ..< 5{
            let person = Person(name: "full name\(i)", age: i+10)
            persons.append(person)
        }

map generate array (0... < 5)

        let persons = (0 ..< 5).map{
            Person(name: "full name\($0)", age: $0+10)
        }

The map here is different from the above usage:

  • The above is to map the existing array of JSON into a new array [Person] with a map
  • Here is no array, but directly use 0... < 5 as an array, but not an array... < note that there should be spaces on both sides of this operator, which represents all numbers in the range of 0 to less than 5. The type is range < int >. You can also call map with this to generate an array

demo download address: click me to download

Keywords: Swift iOS xcode array map

Added by MilesStandish on Fri, 14 Jan 2022 02:57:58 +0200