10 Swift codes that impress Swift program ape

Source: Internet
Author: User
Tags gcd square root

By using a single line of code to do the same 10 exercises, let's take a look at the battle between Swift and other languages.

  

Multiplies the value of each element in the array by 2

Use map to implement

        var arr = [1,2,3,4];        var newArr = arr.map{$0*2} for        item in NEWARR        {            print (item)        }

The code completes the array element by 2 simply and clearly

To find a set of numbers and

This problem can be solved by using the reduce method and the plus operator, because the plus operator is actually a function. But the solution is very obvious, and later we will see reduce more creative use of the method.

        var arr = [1,2,3,4];                Let sum = arr.reduce (0, combine: +)                print (sum)

Retrieving a string containing a word

We use the Contains method to determine if a string contains at least one of the selected keywords:

        Let arr = [' Forrestwoo ', ' Swift1 '] let        str = ' My name is forrestwoo,i am Learning Swift ' let        query = Arr.contains (s tr.containsstring)        print (query)

Read a file

Let path = Nsbundle.mainbundle (). Pathforresource ("Filter", OfType: "RTF")

Let lines = try? String (contentsoffile:path!). characters.split{$0 = = "\ n"}.map (String.init)

For item in lines! {

Print (item)

}

Happy birthday to you
        Let name = "Forrest"        (1...4). Foreach{print ("Happy Birthday" + (($ = = 3)? " Dear \ (Name) ":" To You ")}

This code will "Happy Birthday to You" song lyrics output to the console, it in a period of time the simple use of map functions, but also used the ternary operator.

Array filtering

Suppose we need to split a sequence (sequence) into two parts using a given filter function. In addition to the regular,, and other functions of many languages, map flatMap reduce filter There is a partitionBy function that can do exactly that. As you know, Swift does not have a similar function (we do not want to use the functions in Nsarray here, and to implement the filtering function through nspredicate ).

So, we can SequenceType solve this problem by expanding and adding partitionBy functions to it. We use this function to split an array of integers into two parts:

Extension sequencetype{    typealias Element = Self.Generator.Element         func partitionby (fu: (Element)->bool)- > ([element],[element]) {        var first=[element] ()        var second=[element] () for El in self        {            if Fu (EL) {                first.append (EL)            } else{                second.append (EL)}}        return (First,second)}} let part    = [82, 58, 76, 49, 88, 90]. Partitionby{$0 < 60}part//([58, 49], [82, 76, 88, 90])

In fact, this is not a single line of code, and the use of a command-style solution. Can you use a slight filter improvement on it?

Extension sequencetype{         func anotherpartitionby (fu: (Self.Generator.Element)->bool) ([ Self.generator.element],[self.generator.element]) {        return (Self.filter (FU), Self.filter ({!fu (+)})}    } Let part2 = [82, 76, 88, 90], 90].anotherpartitionby{$0 < 60}PART2//([58, 49], [+].

The solution was slightly better, but he traversed the sequence two times. And for a single-line code implementation, we removed the closed function, which leads to a lot of duplicate content (filter functions and arrays are used in two places).

Can the original sequence be converted using only a single data stream, and the two parts will be stored in a tuple separately? The answer is yes, how to use reduce :

var part3 = [90].reduce ([],[]), combine: {    (A: ([Int],[int]), N:int), [[Int],[int]    ] in (n<60)? (a.0+[n],a.1): (A.0,a.1+[n]) part3//([58, 49], [82, 76, 88, 90])

Here we create a tuple that holds the results, which contains two parts. The elements in the original sequence are then taken out in turn and placed in the first or second section based on the filtered results.

We finally solved the problem with a real one-line code. One thing to note, though, is that we use append methods to construct two-part arrays, so this is actually a bit slower than the first two implementations.

Get and parse network services in XML format

Some of these languages do not need to rely on external libraries, and there are more than one way to work with XML-formatted data (such as Scala itself can parse XML into objects, although the implementation method is clumsy), but the (Swift) Foundation Library only provides a SAX parser, called N Sxmlparser. You may have guessed it: we're not going to use this.

In this case, we can select some open source libraries. Some of these libraries are implemented in C, some are implemented with OBJECTIVE-C, and there are pure Swift implementations.

This time, we're going to use pure Swift to implement the library: AEXML:

Let xmldoc = try? Aexmldocument (Xmldata:nsdata (Contentsofurl:nsurl (string: "Https://www.ibiblio.org/xml/examples/shakespeare/hen_ V.xml ")!) If let Xmldoc=xmldoc {    var prologue = xmldoc.root.children[6]["Prologue" ["SPEECH"]    prologue.children[1]. StringValue//Now all the youth of England is on fire,    prologue.children[2].stringvalue//And silken dalliance in T He wardrobe lies:    prologue.children[3].stringvalue//Now thrive the armourers, and honour ' s thought    Prologue.children[4].stringvalue//Reigns solely in the breast of every man:    prologue.children[5].stringvalue//The Y sell the pasture now to buy the horse,}

Finds the smallest (or largest) element in the array

There are several ways to find the maximum and minimum values in sequence, one of which is the use minElement and maxElement function:

Find the minimum of an array of Ints[10,-22,753,55,137,-1,-279,1034,77].sort (). first[10,-22,753,55,137,-1,- 279,1034,77].reduce (Int.max, Combine:min) [10,-22,753,55,137,-1,-279,1034,77].minelement ()//Find the maximum of an Array of Ints[10,-22,753,55,137,-1,-279,1034,77].sort (). Last[10,-22,753,55,137,-1,-279,1034,77].reduce (Int.min, Combine:max) [10,-22,753,55,137,-1,-279,1034,77].maxelement ()

  

Parallel processing

Some languages support parallel processing of sequences in a simple, transparent way, such as using map and flatMap such functions. This uses the underlying thread pool to speed up multiple operations that are executed sequentially but are independent of each other.

Swift does not yet have such a feature, but we can use GCD to achieve:

Http://moreindirection.blogspot.it/2015/07/gcd-and-parallel-collections-in-swift.html

  

Erato-color-selective sieve method

The ancient and excellent Erato sieve method was used to find all prime numbers less than the given upper limit N.

First, all integers less than n are placed in a sequence (sequence), which removes multiples of each number until all the remaining digits are prime numbers. To speed up execution, we don't actually have to check the multiples of each number, and we can stop when we check the square root of N.

Based on the above definition, the initial implementation might be this:

var n = 50var primes = Set (2...N) (2...Int (sqrt (Double (n))). Foreach{primes.subtractinplace (2*$0). Stride (Through:n, by:$0))}primes.sort ()

In the outer zone, we traverse every number that needs to be checked. For each number, we use the stride(through:Int by:Int) function to calculate the sequence of its multiples. Initially, we constructed a set (set) with all integers from 2 to n, and then subtract the elements from each generated sequence from the collection.

But as you can see, in order to really delete these multiples, we use an externally mutable set, which can cause side effects.

We should always try to eliminate side effects, so we first calculate all the subsequence, then call the flatMap method to expand all of them into a single array, and then remove the integers from the original collection.

var sameprimes = Set (2...N) Sameprimes.subtractinplace ((2...Int (sqrt (Double (n)))                           . flatmap{(2*$0). Stride ( Through:n, By:$0)}) Sameprimes.sort ()

Using destructors to swap values in tuples

Since it is welfare, not everyone knows it. Like other languages that have a tuple type, Swift's tuples can be used to exchange the values of two variables, and the code is simple:

var a=1,b=2 (A, b) = (b,a) a//2b//1

That's all, as we've expected, Swift is as expressive as any other language.

10 Swift codes that impress Swift program ape

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.