设为首页 加入收藏

TOP

给swift程序猿留下深刻印象的10个Swift代码(二)
2017-10-13 10:24:14 】 浏览:8617
Tags:swift 程序 留下 深刻 印象 Swift 代码
s/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, }

 

 

  找到数组中最小(或最大)的元素

我们有多种方式求出 sequence 中的最大和最小值,其中一种方式是使用 minElement 和maxElement 函数:

//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()

 

 

  

   并行处理

某些语言支持用简单透明的方式允许对序列的并行处理,比如使用 map 和 flatMap 这样的函数。这使用了底层的线程池,可以加速多个依次执行但又彼此独立的操作。

Swift 还不具备这样的特性,但我们可以用 GCD 实现:

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

 

  

  埃拉托色尼选筛法

古老而优秀的埃拉托色尼选筛法被用于找到所有小于给定的上限 n 的质数。

首先将所有小于 n 的整数都放入一个序列(sequence)中,这个算法会移除每个数字的倍数,直到剩下的所有数字都是质数。为了加快执行速度,我们其实不必检查每一个数字的倍数,当检查到 n 的平方根时就可以停止。

基于以上定义,最初的实现可能是这样的:

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()

 

在外层的区间里,我们遍历每一个需要检查的数字。对于每一个数字,我们使用stride(through:Int by:Int) 函数计算出由它的倍数构成的序列。最初,我们用所有 2 到 n 的整数构造了一个集合(Set),然后从集合中减掉每一个生成的序列中的元素。

不过正如你所见,为了真正的删除掉这些倍数,我们使用了一个外部的可变集合,这会带来副作用。

我们总是应该尝试消除副作用,所以我们先计算所有的子序列,然后调用 flatMap 方法将其中所有的元素展开,存放到单个数组中,最后再从原始的集合中删除这些整数。

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

 

 

  使用析构交换元组中的值

既然是福利,自然并非每个人都知道这一点。和其他具有元组类型的语言一样,Swift 的元组可以被用来交换两个变量的值,代码很简洁:

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

以上就是全部内容,正如我们预料的那样,Swift 和其他语言一样富有表现力。

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇iOS开发HTTP协议相关知识总结 下一篇【代码笔记】iOS-UIScrollerView..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目