英文版原文地址:http://www.raywenderlich.com/76349/swift-ninja-part-1 英文版
中文翻译版地址:http://www.tairan.com/archives/7303 中文版
总体试了下,这几个挑战出的还是蛮有水平的,对于理解运用Swift的特性很有帮助。
我用Xcode6 Beta5把每个挑战的解答部分都试了下,其中挑战6中的原文有拼写错误,而且@infix部分编译器不能通过:
挑战8使用了currying和偏函数(partial function),很有意思,也算是函数式编程特性的一大特征。
下面是挑战8对数字的一个扩展,有运用闭包
extension Array {
func swapElementAtIndex(index: Int) -> (Int) -> Array {
return { withIndex in
var result = self
if index < self.count && withIndex < self.count{
(result[index], result[withIndex]) = (result[withIndex], result[index])
}
return result
}
}
var arrayWithElementAtIndexToFront: (Int) -> Array {
return swapElementAtIndex(0 as Int)
}
var arrayWithElementAtIndexToBack: (Int) -> Array {
return swapElementAtIndex((self.count-1) as Int)
}
}
调用该函数的示例:
let list = [1, 4, 5, 6, 20, 50] //--> [1, 4, 5, 6, 20, 50] list.arrayWithElementAtIndexToBack(2) //--> [1, 4, 50, 6, 20, 5] list.arrayWithElementAtIndexToFront(4) //--> [20, 4, 5, 6, 1, 50]partial application(偏函数)这块还是有点不好理解的,
var arrayWithElementAtIndexToFront: (Int) -> Array {
return swapElementAtIndex(0 as Int)
}
我的理解:这块swapElementAtIndex:相当于返回了一个匿名函数,而arrayWithElementAtIndexToFront:的参数即为该匿名函数的参数,即swapElementAtIndex:中的withIndex,而其返回值同swapElementAtIndex:的最终返回值一样均为Array,这样是不是清晰一些了?