-2
var firstArray = ["1.","2.","3.","4."]

var secondArray = ["a","b","c"]

func combineTheArrays(array1: [Any], array2: [Any]) -> [Any] {

    var finalArray = [Any]()

    let maxIndex = array1.count >= array2.count ? array1.count : array2.count;

    for i in 0...maxIndex{
        if (array1.count > i){
            finalArray.append(array1[i])
        }
        if (array2.count > i){
            finalArray.append(array2[i])
        }
    } }

combineTheArrays(array1: firstArray, array2: secondArray)

print(finalArray)

I am trying to take two arrays with different/similar types and have it work through the function and combine into one single array. The ideal result of this func is to print:

finalArray = ["1.", "a", "2.", "b", "3.", "c", "4."]
Hamish
  • 78,605
  • 19
  • 187
  • 280
L.Sousa
  • 25
  • 6

1 Answers1

0

You're very close! You just need to return finalArray at the end of your function definition, and then assign the result of the function call, so that you can then use it (such as in a print call):

let finalArray = combineTheArrays(array1: firstArray, array2: secondArray)

print(finalArray)

You should also use generics to ensure that you can handle any kind of elements, so long as their types are the same. Unlike returning Any, your result will be an array of the same type, which will be safer and easier to work with. Here is how I would improve this code:

func combineTheArrays<T>(array1: [T], array2: [T]) -> [T] {

    let maxIndex = max(array1.count, array2.count);

    var finalArray = [T]()
    finalArray.reserveCapacity(array1.count + array2.count)

    for i in 0..<maxIndex {
        if i < array1.count { finalArray.append(array1[i]) }
        if i < array2.count { finalArray.append(array2[i]) }
    }

    return finalArray
}

var firstArray = ["1.","2.","3.","4."]
var secondArray = ["a","b","c"]
let finalArray = combineTheArrays(array1: firstArray, array2: secondArray)

print(finalArray)
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Thank you so much, I spent about 2 hours in total trying different to see how I could get it to print. I have a question though if you could answer, why do I need to make finalArray a constant if I am already making it a variable in the function? – L.Sousa Jun 01 '17 at 23:22
  • Because that variable in the function has absolutely nothing to do with the outside world. It's a local variable that exists only for the duration of the function's lifetime. It's created when the function is called, and it's destroyed when the function is done. – Alexander Jun 01 '17 at 23:26
  • In other words, `let finalArray` being called `finalArray` is merely a coincidence, it has nothing to do with the `var finalArray` local variable of the function. – Alexander Jun 01 '17 at 23:27