做者:Erica Sadun,原文连接,原文日期:2016-06-28
译者:Martin_Joy;校对:bestswifter;定稿:CMBgit
今天的挑战题出自 Swift Users 邮件组的 Adriano Ferreira 。他的出发点是想要简化链式调用,可是不少状况下,想要使代码更 Swifter ,仅仅依靠看起来漂亮的链式语法是不够的。github
func selectionSort(_ array: [Int]) -> [Int] { guard array.count > 1, let minElement = array.min() else { return array } let indexOfMinElement = array.index(of: minElement)! // All of this just to filter out the first smallest element and return the rest // Also tried ‘suffix(from:)' here, but couldn’t make it work properly let rest = array.enumerated() .filter({ index, _ in index != indexOfMinElement }) .map({ _, element in element }) return [minElement] + selectionSort(rest) }
首先,实用性。即便对于零个或一个元素的数组,我不认为添加代码去测试这些条件是实用的。我认为让代码直接顺序执行是更好的选择,即便这样对于只有一个元素的状况不是特别完美。swift
其次,连贯性。我不喜欢先找到最小值,而后再去找它的索引的想法。而枚举是容许将这两个操做串联起来的。数组
第三,风格。数组的遍历应该返回元组类型 (index: Index, value: Element)
。可是示例并无这么作,因此我想要借此机会来扩展数组,使其支持这种类型的元组。同时,个人方案比他须要的答案更复杂一些,由于我想要使用 $0.value
与 $1.index
,而不是使用 $0.1
和 $1.0
。测试
我从新设计的代码在这里,请你也分享你的那一份吧!this
本文由 SwiftGG 翻译组翻译,已经得到做者翻译受权,最新文章请访问 http://swift.gg。翻译