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):
// [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):
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:
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:
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:
[ x1, x2, ... , xn].map(f) -> [f(x1), f(x2), ... , f(xn)]
If you use for in, you need to:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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.