SoFunction
Updated on 2025-04-11

Swift Notes Collection Types

Array

Initialization of repeated values

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

Copy the codeThe code is as follows:

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

Traversal with indexed values

We can use for in to iterate through the array. If we want index, we can use enumerate<Seq: SequenceType>(base: Seq):

Copy the codeThe code is as follows:

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

Assignment and copy

In Swift, arrays and dictionaries are implemented in the form of structures, which is different from the NSArray set, so when assigning values, a copy is actually given:

Copy the codeThe code is as follows:

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

Advanced functions

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

map

map can convert an array into another array according to certain rules, and is defined as follows:

Copy the codeThe code is as follows:

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

That is to say, it accepts a function called transform, and then this function can convert T type into U type and return (that is, (T) -> U), and finally map returns a collection of U type.

The following expressions are more helpful to understand:

Copy the codeThe code is as follows:

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

If you use for in, you need to:

Copy the codeThe code is as follows:

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

For example, we can prefix the numbers in the price array with the ¥ symbol:

Copy the codeThe code is as follows:

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

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

Copy the codeThe code is as follows:

newArray = ({"\($0)€"})

filter

As its name suggests, filter plays the function of filtering. The parameter is a filter closure used to determine whether to filter. It is defined as follows:

Copy the codeThe code is as follows:

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

Let me give you an example to illustrate. First, let’s take a look at the traditional for in implementation method:

Copy the codeThe code is as follows:

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:

Copy the codeThe code is as follows:

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

It was found that the += symbol cannot be used for append, it can only be used for combine, and you can just bread [] outside:

Copy the codeThe code is as follows:

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

(Damn.. I forgot to use filter, and I only found out after writing it.)

Using filter can be implemented like this:

Copy the codeThe code is as follows:

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

You are really short!

reduce

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

Copy the codeThe code is as follows:

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

OK it looks slightly abstract. Let's start with for in. For example, if we want to add all the values ​​in the array into sum, then the traditional way is:

Copy the codeThe code is as follows:

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 initialized value and the other is a closure. The closure has two input parameters, one is the original value and the other is the newly incoming value. The returned new value is the old value in the next round of loop. Let me try some small examples:

Copy the codeThe code is as follows:

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

That's probably it.

map is used to unpack optional types

When we unpack optional types, we usually do this:

Copy the codeThe code is as follows:

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 to implement it:

Copy the codeThe code is as follows:

func increment(someNumber: Int?) -> Int? {
    return { number in number + 1 }
}

increment(5)   // Some 6
increment(nil) // nil

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

Copy the codeThe code is as follows:

func hello(someName: String?) -> String? {
    return { name in "Hello, \(name)"}
}
hello("NatashaTheRobot") // Some "Hello, NatashaTheRobot"
hello(nil) // nil

Then match the ?? symbol, yes, it's basically enough:

Copy the codeThe code is as follows:

func hello(someName: String?) -> String {
    return { name in "Hello, \(name)" } ?? "Hello world!"
}

hello("NatashaTheRobot") // "Hello, NatashaTheRobot"
hello(nil)               // "Hello world!"

Extended

Arrays and dictionaries are very commonly used, but the official method has limited functions. We can learn what is in ExSwift and add some Extension to Array.

The above is the entire content of this article, I hope you like it.