10 swift code that impressed Swift programmers and 10 swift code

Using a single line of code to complete the same 10 exercises, let's take a look at the contest between Swift and other languages.

Multiply 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 simply and clearly completes the multiplication of array elements by 2

Calculate the sum of a group of numbers

You can usereduceMethod and the plus sign operator. This is because the plus sign operator is actually a function. However, this solution is very obvious. We will see it later.reduceMethods are more creative.

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 whether a string contains at least one selected keyword:

let arr = ["ForrestWoo","Swift1"]
let str = "My name is ForrestWoo,I am learning Swift"
let query = arr.contains(str.containsString)
print(query)

Read an object

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 " + (($0 == 3) ? "dear \(name)":"to You"))}

This code will output the lyrics of the song "Happy birthday to you" to the console. It is easy to use within a period of time.mapFunction, and also uses the ternary operator.

Array Filtering

Suppose we need to use a given filter function to divide a sequence into two parts. Many languages except the conventionalmap,flatMap,reduce,filterAnd other functions, there ispartitionByThe function can meet this requirement. As you know, Swift does not have similar functions (we don't want to use them here*NSArray*And*NSPredicate*Implement the filter function ).

Therefore, we can expandSequenceTypeAnd addpartitionByFunction to solve this problem. We use this function to split the integer array 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 uses the imperative solution. Can I use it?filterIs it slightly improved?

extension SequenceType{
func anotherPartitionBy(fu: (Self.Generator.Element)->Bool)->([Self.Generator.Element],[Self.Generator.Element]){
return (self.filter(fu),self.filter({!fu($0)}))
}
}
let part2 = [82, 58, 76, 49, 88, 90].anotherPartitionBy{$0 < 60}
part2 // ([58, 49], [82, 76, 88, 90])

This solution is slightly better, But it traverses the sequence twice. In addition, to implement the function with a single line of code, we delete the closed function, which leads to a lot of repeated content (the filter function and array will be used in two places ).

Can I convert the original sequence with only one data stream, and store the two parts into a single tuples? The answer is yes.reduceMethod:

var part3 = [82, 58, 76, 49, 88, 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 tuples used to save the results. They contain two parts. Then, the elements in the original sequence are retrieved in sequence and put into the first or second part based on the filtering result.

We finally solved this problem with the real single-line code. However, note that we useappendMethod to Construct an array of two parts, so this is actually slower than the first two implementations.

Obtain and parse network services in XML format

Some of the above languages do not need to rely on external libraries. By default, there are more than one solutions for processing data in XML format (for example, Scala itself can parse XML into objects, despite the clumsy implementation method), the (Swift) Foundation Library only provides a SAX Parser called NSXMLParser. You may have guessed that we are not going to use this.

In this case, we can select some open source libraries. Some of these libraries are implemented using C, some are implemented using Objective-C, and some are implemented using pure Swift.

This time, we plan to use the library: AEXML: Implemented by pure Swift:

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 are on fire,
prologue.children[2].stringValue // And silken dalliance in the 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 // They sell the pasture now to buy the horse,
}

Find the smallest (or largest) element in the array

We can find the maximum and minimum values in sequence in multiple ways, one of which is to useminElementAndmaxElementFunction:

//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 and transparent manner. For examplemapAndflatMapSuch a function. This uses the underlying thread pool to accelerate multiple operations that are executed in sequence but independent from each other.

Swift does not yet have such a feature, but we can implement it using GCD:

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

Screening Method of heratosini

The ancient and excellent sieve selection method of heratosini is used to find all the prime numbers smaller than the given upper limit n.

First, all integers less than n are placed in a sequence. This algorithm removes the multiples of each number until all the remaining digits are prime numbers. In order to speed up the execution, we do not have to check the multiples of each number. When we check the square root of n, we can stop it.

Based on the above definition, the initial implementation may be as follows:

var n = 50
var primes = Set(2...n)
(2...Int(sqrt(Double(n)))).forEach{primes.subtractInPlace((2*$0).stride(through:n, by:$0))}
primes.sort()

In the outer range, we traverse every number to be checked. For each number, we usestride(through:Int by:Int)Function compute the sequence composed of its multiples. Initially, we constructed a Set with all the integers 2 to n, and then removed the elements in each generated sequence from the Set.

But as you can see, in order to delete these multiples, we use an external variable set, which brings side effects.

We should always try to eliminate the side effects, so we should calculate all the subsequences and then callflatMapMethod to expand all the elements, store them in a single array, and then delete these integers from the original set.

var sameprimes = Set(2...n)
sameprimes.subtractInPlace((2...Int(sqrt(Double(n))))
.flatMap{ (2*$0).stride(through:n, by:$0)})
sameprimes.sort()

Use destructor to exchange values in tuples

Since it is welfare, not everyone knows this. Like other languages with tuples, Swift tuples can be used to exchange values of two variables. The code is concise:

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

The above is all content. As we expected, Swift is as expressive as other languages.