Swift Notes Collection type _swift

Source: Internet
Author: User
Tags arrays closure unpack

Array

Initialization of duplicate values

In addition to the normal initialization method, we can initialize an array and populate the duplicate values through init (Count:int, repeatedvalue:t):

Copy Code code as follows:

[0.0,0.0,0.0]
var threedoubles = [Double] (count:3,repeatedvalue:0.0)

Traversal with index values

We can iterate over the array using for, and if we want to index, we can use Enumerate<seq:sequencetype> (BASE:SEQ):

Copy Code code 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 structs, unlike Nsarray, so assigning a value is actually a copy:

Copy Code code as follows:

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. You can save a lot of unnecessary code if you use it properly.

Map

A map can convert an array into another array, defined as follows:

Copy Code code as follows:

Func map<u> (Transform: (T)-> U)-> u[]

That is, it takes a function called transform, and then this function converts the T-type to a U-type and returns (i.e. (T)-> u), and the final map returns a set of type U.

The following expressions are more helpful to understand:

Copy Code code as follows:

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

This is required if you are implementing with for in:

Copy Code code as follows:

var newarray:array<t> = []
For item in Oldarray {
NewArray + F (item)
}

For example, we can add the ¥ symbol to the number in the price array:

Copy Code code as follows:

var oldarray = [10,20,45,32]
var NewArray = Oldarray.map ({Money in "¥\"})
println (NewArray)//[¥10,¥20,¥45,¥32]

If you think money in is also a bit superfluous, you can use $:

Copy Code code as follows:

NewArray = Oldarray.map ({"\ ($)?"})

Filter

Methods such as the name, filter is the function of filtering, parameter is a filter to determine whether the screen closure, defined as follows:

Copy Code code as follows:

Func Filter (includeelement: (t)-> Bool)-> [t]

Let's give an example to illustrate. First look at the traditional for-in implementation approach:

Copy Code code as follows:

var oldarray = [10,20,45,32]
var filteredarray:array<int> = []
For Oldarray {
if (Money > 30) {
Filteredarray + = Money
}
}
println (Filteredarray)

The odd thing is that the code here doesn't compile:

Copy Code code as follows:

Playground execution failed: <expr>:15:9: Error: ' array<int> ' isn't identical to ' UInt8 '
Filteredarray + = Money

found that the original = = = Symbol can not be used for append, can only be used for combine, outer bread [] can:

Copy Code code as follows:

var oldarray = [10,20,45,32]
var filteredarray:array<int> = []
For Oldarray {
if (Money > 30) {
Filteredarray + = [Money]
}
}
println (Filteredarray)//[45, 32]

(Rely on. Actually forgot to put the use of filter, write to find later. )

This can be done with filter:

Copy Code code as follows:

var oldarray = [10,20,45,32]
var Filteredarray = Oldarray.filter ({
return $ > 30
})
println (Filteredarray)//[45, 32]

You are so short!

Reduce

The reduce function solves the problem of consolidating values from an array into a separate object. The definition is as follows:

Copy Code code as follows:

Func reduce<u> (Initial:u, Combine: (U, T)-> u)-> u

Well, it looks a little abstract. Let's start with for. For example, to add the values in an array to sum, the traditional approach is:

Copy Code code as follows:

var oldarray = [10,20,45,32]
var sum = 0
For Oldarray {
sum = sum + Money
}
println (SUM)//107

Reduce has two parameters, one is the initialized value, the other is a closure, the closure has two input parameters, one is the original value, one is the new entry value, and the new value returned is the old value in the next round loop. Write a few small examples to try:

Copy Code code as follows:

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

That's probably it.

Map is used to unpack the optional type

We usually do this when we unpack the optional types:

Copy Code code 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 achieve:

Copy Code code as follows:

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:

Copy Code code as follows:

Func Hello (somename:string?)-> String? {
Return Somename.map {name in "Hello, \ (name)"}
}
Hello ("Natashatherobot")//Some "Hello, Natashatherobot"
Hello (nil)//nil

To match up with?? Symbol, well basically enough:

Copy Code code as follows:

Func Hello (somename:string?)-> String {
Return Somename.map {name in "Hello, \ (name)"}?? "Hello world!"
}

Hello ("Natashatherobot")//"Hello, Natashatherobot"
Hello (nil)//"Hello world!"

Extended

Arrays and dictionaries are very common, and the official method has limited functionality. We can learn the contents of Array.swift in Exswift and add some Extension to the Array.

The above mentioned is the entire content of this article, I hope you can enjoy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.