title: “Why coding like This —— Map 函数揭秘”
date: 2015-08-02 23:24:16
categories: “why coding like this”
tags: [swift进阶]
1.Map函数揭秘
Topic 1:
请用Map函数实现对一个Int类型数组的元素进行2倍放大。
Example:
//例一
let intArray = [1,2,3]
var result = intArray.map{ $0 * 2} //输出[2,4,6]
why coding like this?
假设让你写一个函数,传入参数为Int类型数组,对数组内每一个元素进行放大2倍操作,然后将处理后的数组作为结果返回。
这不难实现,只需要使用for-in
语句遍历数组元素,进行放大处理并保存结果值,最后返回处理后的数组。代码如下:
//例二:
func doubleArrayByTwo(xs:[Int])->[Int]{
var result :[Int] = []
for x in xs{
result.append(x * 2)
}
return result
}
不妨来试试写的函数: