A few years ago, an article that stated "10 Scala functional single-line code" was very popular, and then other language versions immediately appeared, such as Haskell version, Ruby version, Groovy version, Clojure version, Python version, C# version, F# version, CoffeeScript version, etc.
We don't know how many people are really impressed by this single line of code, but I think this will inspire you to learn more about functional programming.
1 Multiply each element in the array by 2
It's very simple, especially if you use map to solve it.
(1...1024).map{$0 * 2}
2 Sum of elements in array
Although the reduce and plus operators are used here, with the help of the fact that the plus operator is a function, the solution is obvious and we can see a more creative usage of reduce.
(1...1024).reduce(0,combine: +)
3 Verify whether the specified word exists in the string
Let's use filter to verify that the tweet contains one of several selected keywords:
let words = ["Swift","iOS","cocoa","OSX","tvOS"] let tweet = "This is an example tweet larking about Swift" let valid = !({($0)}).isEmpty valid //true
Update: @oisdk proposes some better options:
()
The method is simpler, and there is one:
.split(" ") .lazy .map() .contains(Set(words).contains)
4 Read the file
Like other languages, it is impossible to read files into arrays with simple built-in, but we can use split and map to create some short code that does not require a for loop:
let path = ().pathForResource("test", ofType: "txt") let lines = try? String(contentsOfFile: path!).{$0 == "\n"}.map() if let lines=lines { lines[0] // O! for a Muse of fire, that would ascend lines[1] // The brightest heaven of invention! lines[2] // A kingdom for a stage, princes to act lines[3] // And monarchs to behold the swelling scene. }
The last step of the map and string constructor converts our array characters into strings.
5 Happy birthday to you!
This will display Happy Birthday Songs to the console, through maps and simple use of range and ternary operators.
let name = "uraimo" (1...4).forEach{print("Happy Birthday " + (($0 == 3) ? "dear \(name)":"to You"))}
6 Filter numbers in array
In this case, we need to partition a sequence using the provided filter function. In addition to the commonly used map, flatMap, reduce, filter, etc., many languages also have partitionBy functions that happen to do this. As you know, Swift has nothing like this (the filterable NSArray function provided by NSPredicate is not what we need here).
Therefore, we can solve this problem by extending SequenceType with the partitionBy function, and we will use the partitionBy function to partition the integer array:
extension SequenceType{ typealias Element = func partitionBy(fu: (Element)->Bool)->([Element],[Element]){ var first=[Element]() var second=[Element]() for el in self { if fu(el) { (el) }else{ (el) } } return (first,second) } } let part = [82, 58, 76, 49, 88, 90].partitionBy{$0 < 60} part // ([58, 49], [82, 76, 88, 90])
Not really single-line code. So, can we use filters to improve it?
extension SequenceType{ func anotherPartitionBy(fu: ()->Bool)->([],[]){ return ((fu),({!fu($0)})) } } let part2 = [82, 58, 76, 49, 88, 90].anotherPartitionBy{$0 < 60} part2 // ([58, 49], [82, 76, 88, 90])
A little bit better, but it goes through the sequence twice and trying to turn it into a single line of code to remove closures will result in too many duplications (the filtering function and array will be used in both places).
Do we use a single data stream to build something that can convert the initial sequence into a partitioned tuple? Yes, we can use reduce.
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 build a result tuple containing two partitions, one element at a time, test each element in the initial sequence using the filter function, and append that element to the first or second partition array based on the filter results.
Finally, I get the real single line of code, but be aware of the fact that the partitioned array is constructed by appendages, which actually makes it slower than the previous two implementations.
7 Get and parse XML Web Services
Some of the languages above do not rely on external libraries and provide multiple options to handle XML by default (e.g. Scala is clumsy but "native" support XML parsing to objects), but Foundation only provides the SAX parser NSXMLParser, and as you might have guessed, we are not going to use it.
There are several alternative open source libraries that we can use in this case, some of which are written in C or Objective-C and others are pure Swift.
This time, we intend to use pure Swift AEXML:
let xmlDoc = try? AEXMLDocument(xmlData: NSData(contentsOfURL: NSURL(string:"/xml/examples/shakespeare/hen_v.xml")!)!) if let xmlDoc=xmlDoc { var prologue = [6]["PROLOGUE"]["SPEECH"] [1].stringValue // Now all the youth of England are on fire, [2].stringValue // And silken dalliance in the wardrobe lies: [3].stringValue // Now thrive the armourers, and honour's thought [4].stringValue // Reigns solely in the breast of every man: [5].stringValue // They sell the pasture now to buy the horse, }
8 Find the smallest (or maximum) value in an array
We have various ways to find the minimum and maximum values in a sequence, including the minElement and maxElement functions:
//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(, 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(, combine: max) [10,-22,753,55,137,-1,-279,1034,77].maxElement()
9 Parallel processing
Some languages allow for the enablement of array pairing functions in a simple and transparent way, such as parallel processing of map and flatMap, to speed up the execution of sequential and independent operations.
This feature is not available in Swift yet, but can be built using GCD:/2015/07/
10 Elatostney Screening Method
The Elatostney sieve method is used to find all prime numbers until the given upper limit n.
Starting with all sequences of integers smaller than n, the algorithm deletes multiples of all integers until only prime numbers are left. And to speed up execution, we don't actually need to check the multiples of each integer, we just need to stop at the square root of n.
According to this definition, the first execution might look like this:
var n = 50 var primes = Set(2...n) (2...Int(sqrt(Double(n)))).forEach{((2*$0).stride(through:n, by:$0))} ()
We use an external range to iterate over the integers we want to check, and for each integer we use stride(through:Int by:Int) to calculate a sequence of multiples of the numbers. Those sequences are then subtracted from the Set, which is initialized with all integers from 2 to n.
But as you can see, in order to actually remove multiples, we use an external variable Set, resulting in collateral consequences.
To eliminate the collateral consequences, as we should usually do, we will first calculate all the sequences, flatMap them with a single array of multiples, and remove these integers from the initial Set.
var sameprimes = Set(2...n) ((2...Int(sqrt(Double(n)))) .flatMap{ (2*$0).stride(through:n, by:$0)}) ()
A cleaner way, use a good example of flatMap to generate flat nested arrays.
11 Others: Deconstructing tuple swaps
Last but not everyone knows that like other languages with tuple type, tuples can be used to perform compact variable swaps:
var a=1,b=2 (a,b) = (b,a) a //2 b //1
OK, as expected, Swift is as expressive as other languages.
Do you have other interesting Swift single-line codes you want to share? Let’s talk about it together!
Original English:10 Swift One Liners To Impress Your Friends
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.