w3resource
swift Programming Exercises

Swift Array Programming Exercises: Create a new array of length 2 containing the middle elements from two give array of integers and length 3

Swift Array Programming: Exercise-9 with Solution

Write a Swift program to create a new array of length 2 containing the middle elements from two give array of integers and length 3.

Pictorial Presentation:

Swift Array Programming Exercises: Create a new array of length 2 containing the middle elements from two give array of integers and length 3

Sample Solution:

Swift Code:

func middle_element(_ a: [Int], _ b: [Int]) -> [Int] {
    var new_array: [Int] = []
    new_array.append(a[1])
    new_array.append(b[1])
    
    return new_array
}

print(middle_element([1, 2, 3], [4, 5, 6]))
print(middle_element([7, 7, 7], [3, 8, 0]))
print(middle_element([5, 2, 9], [1, 4, 5]))

Sample Output:

[2, 5]
[7, 8]
[2, 4]

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to compute the sum of the first 2 elements of a given array of integers. Return 0 if the length of the given array is 0 and return the first element value If the array length is less than 2.
Next: Write a Swift program to create a new array of length 2 containing the first and last elements from a given array of integers. The given array length must be 1 or more.

What is the difficulty level of this exercise?