Array is one of the most commonly used data types in development. The official document defines Array as: An ordered, random-access collection. It usually refers to an ordered set, not the size order, but the sequential position of the elements in the Array.

1, Swift way to manipulate arrays

  • N methods for creating an Array
var testArray1: Array<Int> = Array<Int> ()var testArray2: [Int] = []
var testArray3 = [Int] ()var testArray4 = testArray3
Copy the code

In the above code block, there is no essential difference between Array

and [Int](); either method can be used to initialize an Array. The last one directly uses an empty Array to generate a new Array object.

  • A method that specifies an initial value while defining an array
var testInts = [Int](repeating: 6, count: 3) // [6, 6, 6]
var sixInts = testInts + testInts // [6, 6, 6, 6, 6, 6]
Copy the code
  • Count and isEmtpy attributes

    Count returns the number of elements in the array collection of type Int

    let testArray = ["one","two","three","four","five","six"]
    let countInts = testArray.count // 6
    Copy the code

    IsEmpty indicates whether the array isEmpty and it’s a Bool so we can check whether the array isEmpty before we do anything with it

let testArray = ["one","two","three","four","five","six"] if testArray.isEmpty == false { let mapArray = testArray.map({ (mapString) -> String in return mapString})} else {print(" array empty ")}Copy the code
  • Accesses elements in an Array

  • Access an element of an array by index

Index is commonly used in almost all developing language (or subscript) access to an array of the elements in the array, because when we access array element using the index can not guarantee the security of the index, so this way the risk of an array, a bit not note will lead to the entire program Crash directly, thereby having a bad experience to the user. Swift also supports this, but Apple doesn’t recommend using this method to access array elements.

let testArray = ["one","two","three","four","five","six"]
let sevenStr = testArray[7]
Copy the code

Fatal error: Thread 1: Fatal error: Fatal error: Index out of range, so you should be careful when using an Index to access array elements. So how do you gracefully access array elements in Swift? In fact, Swift’s designers discourage developers from using subscripts like this.

If you use the type method, you can see that the value returned by this method is String, which means that you need to make sure that the value you get is String, not Optionals

. When we use this method, we don’t have Optionals protecting the array out of bounds. When we use the subscript method we run the risk of crashing.

  • Accesses elements in a range of arrays

    In Swift, we can access A range of the Array by using the range operator, which is not an Array, but an ArraySlice, which is defined as A slice of an in the official document Array, ContiguousArray, or ArraySlice instance. In plain English, an Array View does not hold the contents of the Array, but only the range of the Array referenced by the View. We can create a new Array from this view.

    let testArray = ["one","two","three","four","five","six"]
    let rangeArray = Array(testArray[0...2])
    Copy the code
  • Add or remove elements to an array

    To add an element to the end of an array, use the append method, or use += :

    var testArray = ["one","two","three","four","five","six"]
    testArray.append("seven") // ["one", "two", "three", "four", "five", "six", "seven"]
    testArray += ["eight","nine"] // ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    Copy the code

    To add elements in the middle of an Array, use the insert method:

    var testArray = ["one","three","four","five","six"]
    testArray.insert("two", at: 1) // ["one","two","three","four","five","six"]
    testArray.insert("seven", at: 7) // Thread 1: Fatal error: Array index is out of range`
    Copy the code

The first parameter of the insert method is the value to be inserted, and the second parameter is the index of the position to be inserted. Array1. endIndex, which causes the program to Crash if it goes beyond this range

Delete an element from an array:

Remove the last element in the array using the removeLast() method, and remove the first element from the array using the removeFirst() method.

var testArray = ["one","two","three","four","five","six","seven"]
testArray.removeLast() // ["one","two","three","four","five","six"]
testArray.removeFirst() // ["two","three","four","five","six"]
testArray.remove(at: 7) // Fatal error: Index out of range
var secondTestArray = [String]()
secondTestArray.removeFirst() // Fatal error: Can't remove first element from an empty collection
secondTestArray.removeLast() // Fatal error: Can't remove last element from an empty collection
secondTestArray.popLast() // nil 
Copy the code

When deleting an element from an array, first make sure that the array is not empty, then make sure that the index to be deleted is within the legal range, and then delete it

Find the position of an element in an array:

If I want to find the position of element 5 in an array, I can use firstIndex and return an Optional

FirstIndex {$0 == 5} print("ondexIndex===============\(oneIndex) ?? 0))"Copy the code
  • Array traversal

    Traversal of each element of an Array is also common in development:

    • (1) The simplest way
    let testArray = ["one","two","three","four","five","six"]
    for vaule in testArray {
        print(vaule)
    }
    Copy the code
    • (2) While traversing, obtain both the index and the value

      Use the enumerated() method of an array object, which returns a Sequence object containing the index and value of each member.

     let testArray = ["one","two","three","four","five","six"]
     for (index, value) in testArray.enumerated() {
        print("\(index): \(value)")
     }
    Copy the code
  • (3) Traversal through closure

    With closure, we can use Array’s forEach method to iterate over a set of numbers:

let testArray = ["one","two","three","four","five","six"]
    testArray.forEach { (vaule) in
        print(vaule)
    }
Copy the code

For in has the same effect as forEach traversal, but if you use forEach to traverse the array, you can’t exit the loop by breaking or continuing, and you can only exit the loop by using the for in method.

testArray.forEach { (testChar) in
 if testChar == "three" {
        continue // 'continue' is only allowed inside a loop
    }
 }
Copy the code
  • (4) Map, flatMap, compactMap, filter traversal number group

In fact, Swift’s designers don’t recommend using the traditional C-style for loop. Swift provides a more advanced way for developers to loop through an array using maps and filters, depending on their needs.

Example 1: The teacher has now got the students’ test scores, and adds 30 points to each student’s usual score to get the students’ final score. If the traditional C language loop is used:

let fractionArray: [Int] = [40,53,59,43,56,54,33,55,66,70,22,69] var finallyList = (Int) () for num in fractionArray { finallyList.append(num + 30) } // [70, 83, 89, 73, 86, 84, 63, 85, 96, 100, 52, 99]Copy the code

Take a look at Swift’s map method for developers:

Let fractionArray: [Int] = [40,53,59,43,56,54,33,55,66,70,22,69] let finallyArray: [Int] = fractionArray.map { return $0 + 30 } // [70, 83, 89, 73, 86, 84, 63, 85, 96, 100, 52, 99]Copy the code

A map is used to transform all the elements of an array according to specified rules and return a new array, which is more expressive than using a for loop.

usemapTo do this, greatly improving the readability of the code; At the same time usemapReturns an array of constants directly;

Of course, Swift’s designers only encapsulated the map code for the loop, the core code is as follows:

extension Array {
 public func myselfMap<T>(_ transform: (Element) -> T) -> [T] {
      var tmp: [T] = []
      tmp.reserveCapacity(count)
     
      for value in self {
          tmp.append(transform(value))
      }
      return tmp
   }
}  
Copy the code

FlatMap and compactMap are updated versions of Map:

  • FlatMap traversal turns a two-dimensional array into a one-dimensional array.

  • CompactMap removes nil values while iterating through the array.

Let testList = [1,2,2,3,3,4,nil,5,6] let lsArray: [Int] = testList.compactMap { (num) -> Int? in return num }// [1, 2, 2, 3, 3, 4, 5, 6]Copy the code

Example 2: After calculating students’ scores, the teacher wants to check which students’ scores are excellent. In this case, we can use filter

    let excellentArray = finallyArray.filter {
       $0 >= 85
    }
    // [89, 86, 85, 96, 100, 99]
Copy the code

A map iterates through an array of numbers and returns a new array with a specified rule for each parameter. Filter simply iterates through the array according to the specified rule and returns a new array

How is filter implemented? We can implement it according to the implementation method of Map, and its core code is as follows:

extension Array {
 func myfilter(_ predicate: (Element) -> Bool) -> [Element] {
     var tmp: [Element] = []
     for value in self where predicate(value) {
         tmp.append(value)
     }
     return tmp
 }
}
Copy the code
  • (5)、min 、 max

As long as the elements in the array implement Equatable Protocol, the developer does not need to perform any operations on the array, but can directly call min and Max:

finallyArray.min() // 52
finallyArray.max() // 100
Copy the code
  • sortedandpartitionSort the array

Then, if the teacher to the class results according to the order from large to small or from small to large, it can be more intuitive to see the results of the class:

let mixArray = finallyArray.sorted() // [52, 63, 70, 73, 83, 84, 85, 86, 89, 96, 99, 100]
let maxArray = finallyArray.sorted(by: >) // [100, 99, 96, 89, 86, 85, 84, 83, 73, 70, 63, 52]
Copy the code
  • Determines whether two arrays are equal
finallyArray.elementsEqual(mixArray, by: {
    $0 == $1
}) // false
Copy the code
  • Whether the array starts with a particular sort

If the teacher wants to calculate the score of this exam, is there a full mark:

mixArray.starts(with: [100], by: {
    $0 == $1
}) // true
Copy the code
  • Evaluates the sum of elements in an array

For example, the teacher wants to calculate the total score of the test and then calculate the average score of the test:

If we use the C language style, we will first do a traversal of the score, and then sum up to get the total score of the class:

var allNum = Int()
for num in finallyList {
   allNum = allNum + num
}
allNum / (finallyList.count)
Copy the code

Swift offers developers a simpler and more effective way to do this:

finallyList.reduce(0, +) / (finallyList.count) // 81
Copy the code
  • Sort the elements of an array by conditions

For example, the teacher has to calculate the score of pass and fail respectively. We consider 60 to be pass:

let pass = mixArray.partition(by: {
  $0 > 60
})
let failedArray = mixArray[0 ..< pass] // 不及格的 [52]
let passArray = mixArray[pass ..< mixArray.endIndex] // 及格的 [63, 70, 73, 83, 84, 85, 86, 89, 96, 99, 100]
Copy the code

Array and NSArray

  • Array is a structure, which is a value type, and NSArray is a class, which is a reference type.

  • Whether an Array can be modified is determined solely by the var and let keywords; the Array type itself does not resolve whether it can be modified.

  • How does Array convert to NSArray

    How to convert a Swift array to NSArray?

  • Memory at assignment time

    Take a look at the following two pieces of code

    (1) Array copy

    var testArray = ["one","two","three","four","five","six"] let copyArray = testArray testArray.append("seven") // ["one",  "two", "three", "four", "five", "six", "seven"] print(copyArray) // ["one", "two", "three", "four", "five", "six"]Copy the code

    (2), NSArray copy

    let mutArray = NSMutableArray(array: ["one","two","three","four","five","six"])
    let copyArray: NSArray = mutArray
    mutArray.insert("seven", at: 6) // ["one", "two", "three", "four", "five", "six", "seven"]
    print(copyArray) // ["one", "two", "three", "four", "five", "six", "seven"]
    Copy the code

    In the first code: If you copy the testArray Array and add elements to the testArray Array, the contents of a copyArray don’t change, because when you copy the testArray Array, you don’t copy the contents, you copy the memory address, and both arrays still share the same memory address, and only if you change the contents of one Array, A new memory is generated.

    Second code: Copy the mutArray array, even though MY copyArray is an NSArray, I expect that the value of my copyArray will not change, but actually when I change the value of my mutArray my copyArray will change. Since this assignment performs a reference copy, the two arrays point to the same memory address, so when we modify the contents of the mutArray, the copyArray is indirectly affected.

    • The Swift var and let keywords do not work when we use NSArray and NSMutableArray.

    This article mainly introduces some basic usage of Swift’s most common Array, and objective-C NSArray differences.

    Links:

    Apple developer Array

    Swift 3 Collections

    Geek Time: Collection class