When writing a universal function, it is sometimes easier to approach it in 3 stages: first write the code offline using a certain type. Then write the code as a function, still with a specific type. Finally, change the function to be shared.
The first part, dividing the array by 3, can be done as follows:
let a = [1,2,3,4,5]
Note that the restriction you provide between { } is an operation that will be applied to each element of the array. $0 represents an element, and you divide it by 3. You can also write it as a.map { i in i / 3 } .
To include this in your own function:
func divideby3Map(source: [Int]) -> [Int] { return source.map { $0 / 3 } }
No need to declare a new array - map will create it for you. Then you can return it directly (you can assign it to a temporary one if you want, but it really is not necessary).
Finally, if you want to make it general, start by adding a placeholder:
func divideby3Map<T>(source: [T]) -> [T] { return source.map { $0 / 3 } }
Note: one placeholder requires T , because you are returning the same type that you passed.
In addition, this compiler does not compile because the compiler does not know that T guaranteed to provide two critical things: the ability to divide (the / operator) and the ability to create new T from whole literals (i.e. create T with a value of 3 to divide by) . Otherwise, what if we passed an array of strings or an array of arrays to?
To do this, we need to "limit" T , so our function will only accept the types of arguments that these functions provide. One of these protocols that we can use to limit T is IntegerType , which guarantees these functions (as well as some others, such as + , * , etc.):
func divideby3Map<T: IntegerType>(source: [T]) -> [T] { return source.map { $0 / 3 } } divideby3Map(a) // returns [0,0,1,1,1] let smallInts: [UInt8] = [3,6,9] divideby3Map(smallInts) // returns [1,2,3]