[Swift] Day03: set type, swiftday03

Source: Internet
Author: User

[Swift] Day03: set type, swiftday03
Initialization of repeated array values of the collection type

In addition to common initialization methods, we can useinit(count: Int, repeatedValue: T)To initialize an array and fill in the repeated values:

// [0.0,0.0,0.0]var threeDoubles = [Double](count:3,repeatedValue:0.0)
Traversal with index value

We can usefor inTraverse the array. if you wantindexYou can useenumerate<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 in the form of struct, andNSArrayThe set is not the same, so the assignment actually gave a copy:

let hd = Resolution(width: 1920, height: 1080)var cinema = hdcinema.height = 233cinema  // 1920 233hd      // 1920 1080
High-order functions

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

Map

mapYou can convert an array into another array according to certain rules. The definition is as follows:

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

That is to say, it accepts a function calledtransformThen, this function can convert T type to U type and return (that is(T) -> U), And finallymapReturns a set of U types.

The following expressions are more helpful:

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

If you usefor inTo achieve this, you need:

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

For example, we can add the ¥ symbol before the numbers in the price array:

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

If you thinkmoney inYou can also use$0:

newArray = oldArray.map({“\($0)€”})
Filter

Method as its name,filterThe filter function is used. The parameter is a filter closure used to determine whether or not to filter. It is defined as follows:

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

Let's give an example. First, let's take a look at the traditionalfor inImplementation Method:

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

The strange thing is that the code compilation here fails:

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

It turns out that+=Symbol cannot be usedappend, Can only be usedcombine, Bread[]You can:

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

reduceThe function solves the problem of integrating values in the array into an independent object. Definition:

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

It looks a little abstract. We are still fromfor inStart. For example, we need to add all the values in the arraysumSo the traditional approach is:

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

reduceThere are two parameters, one is the initial value, the other is a closure, and the closure has two input parameters, the other is the original value, and the other is the new value, the new value returned is the old value in the next cycle. Write a few small examples to give it a try:

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

This is probably the case.

Extension

Arrays and dictionaries are commonly used, but official methods have limited functions. We can learn the content of Array. swift in ExSwift and add some Extension to Array.

References
  • Collection Types
  • ExSwift/Array. swift
  • Higher Order Functions: Map, Filter, Reduce and more-Part 1
  • {(Int)} is not identical to UInt8

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.