Collection type of Swift notes

  • 2020-05-10 22:59:37
  • OfStack

An array of

Initialization of duplicate values

In addition to the normal initialization method, we can initialize an array by init(count: Int, repeatedValue: T) and fill it with duplicate values:


// [0.0,0.0,0.0]
var threeDoubles = [Double](count:3,repeatedValue:0.0)

Traversal with indexed values

We can traverse groups using for in, or enumerate if we want index < Seq : SequenceType > : (base Seq) :


let arr = ["a","b"]
for (index, value) in enumerate(arr) {
    println("\(index):\(value)")
}
// 0:a
// 1:b

Assignment and copy

Arrays and dictionaries in Swift are implemented as structs, which is not quite the same as the one in NSArray, so the assignment is actually a copy:


let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
cinema.height = 233
cinema  // 1920 233
hd      // 1920 1080

Higher-order functions

Swift has some Higher Order Functions: map, filter and reduce. Used correctly, you can save a lot of unnecessary code.

map

map can convert one array into another array according to the rules set by 1, as follows:


func map<U>(transform: (T) -> U) -> U[]

That is, it accepts a function called transform, which converts T to U and returns (T) - > U), and finally map returns a collection of type U.

The following expression is more helpful to understand:


[ x1, x2, ... , xn].map(f) -> [f(x1), f(x2), ... , f(xn)]

If you use for in, you need this:


var newArray : Array<T> = []
for item in oldArray {
    newArray += f(item)
}

For example, we can put the price array before all the Numbers by adding the ¥symbol:


var oldArray = [10,20,45,32]
var newArray = oldArray.map({money in " RMB \(money)"})
println(newArray) // [ RMB 10, RMB 20, RMB 45, RMB 32]

If you find money in a bit redundant, you can use $0:


newArray = oldArray.map({"\($0) � })

filter

As the name suggests, filter performs the function of filtering. The parameter is a filter closure that can be used to determine whether the filter is removed or not. It is defined as follows:


func filter(includeElement: (T) -> Bool) -> [T]

So let me give you an example of 1. Let's start with the traditional for in implementation:


var oldArray = [10,20,45,32]
var filteredArray : Array<Int> = []
for money in oldArray {
    if (money > 30) {
        filteredArray += money
    }
}
println(filteredArray)

Strangely, the code here does not compile well:


Playground execution failed: <EXPR>:15:9: error: 'Array<Int>' is not identical to 'UInt8'
        filteredArray += money

It was found that the symbol += could not be used for append, but only for combine. You can use it for [] outside:


var oldArray = [10,20,45,32]
var filteredArray : Array<Int> = []
for money in oldArray {
    if (money > 30) {
        filteredArray += [money]
    }
}
println(filteredArray) // [45, 32]

(by.. I forgot to post filter until later.

You can do this with filter:


var oldArray = [10,20,45,32]
var filteredArray  = oldArray.filter({
    return $0 > 30
})
println(filteredArray) // [45, 32]

You are so short!

reduce

The reduce function solves the problem of integrating the values in an array into a single object. The definition is as follows:


func reduce<U>(initial: U, combine: (U, T) -> U) -> U

Well, it looks a little abstract. Let's start with for in again. For example, if we want to add up all the values in an array to sum, the traditional way is:


var oldArray = [10,20,45,32]
var sum = 0
for money in oldArray {
    sum = sum + money
}
println(sum) // 107

reduce has two parameters, one is the initial value and the other is a closure. The closure has two input parameters, one is the original value, one is the new value, and the new value returned is the old value in the next cycle. Write a few small examples and try 1:


var oldArray = [10,20,45,32]
var sum = 0
sum = oldArray.reduce(0,{$0 + $1}) // 0+10+20+45+32 = 107
sum = oldArray.reduce(1,{$0 + $1}) // 1+10+20+45+32 = 108
sum = oldArray.reduce(5,{$0 * $1}) // 5*10*20*45*32 = 1440000
sum = oldArray.reduce(0,+) // 0+10+20+45+32 = 107
println(sum)

That's about it.

map is used to unpack optional types

Here's what we usually do when unpacking optional types:


func increment(someNumber: Int?) -> Int? {
    if let number = someNumber {
        return number + 1
    } else {
        return nil
    }
}
increment(5)   // Some 6
increment(nil) // nil

We can also use map:


func increment(someNumber: Int?) -> Int? {
    return someNumber.map { number in number + 1 }
} increment(5)   // Some 6
increment(nil) // nil

It is also possible to include other optional types, such as String:


let arr = ["a","b"]
for (index, value) in enumerate(arr) {
    println("\(index):\(value)")
}
// 0:a
// 1:b
8

Add ? The & # 63; Symbols, well, basically enough:


let arr = ["a","b"]
for (index, value) in enumerate(arr) {
    println("\(index):\(value)")
}
// 0:a
// 1:b
9

extension

Arrays and dictionaries are commonly used for 10 cents, while the official methods have limited functionality. We can learn about Array.swift in ExSwift and add some Extension to Array.

That's all for this article, I hope you enjoy it.


Related articles: