How to format this Swift function properly for array matching?

I am trying to create a quick function that will display an array, divide each value in the array by 3, and then spit out a new array. This is what I have so far:

func divideby3Map<T, U>(y: [T], z: T -> U) -> [U] { let array = [int]() let divideby3Array = array.map { [y] / 3 } return dividedby3Array } divideby3Map([1,2,3,4,5]) 

Where T and U are the original array, and the new array is returned accordingly, and it is executed using generics.

I am sure that it is spelled incorrectly, I adhere to the correct syntax. For example, since the returned array is represented by the common [U] , I assume that I should use it somewhere in the returned array, but I don’t know where it was.

+5
source share
1 answer

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] // map is run on the array of integers, and returns a new // array with the operation performed on each element in a: let b = a.map { $0 / 3 } // so b will be [0,0,1,1,1] // (don't forget, integer division truncates) 

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] 
+7
source

All Articles