w3resource

Swift Array Programming Exercises: Create a new array, taking first two elements from a given array of integers


Write a Swift program to create a new array, taking first two elements from a given array of integers. If the length of the given array is less than 2 use the single element of the given array.

Pictorial Presentation:

Swift Array Programming Exercises: Create a new array, taking first two elements from a given array of integers

Sample Solution:

Swift Code:

func new_array(_ a: [Int]) -> [Int] {
    guard a.count > 1 else 
    {
        return a
    }
    
    return Array(a.prefix(2))
}
print(new_array([0, 1, 2, 3, 4]))
print(new_array([0, 1, 2]))
print(new_array([0]))

Sample Output:

[0, 1]
[0, 1]
[0]

Go to:


PREV : Write a Swift program to create a new array of length 3 containing the elements from the middle of a given array of integers and length will be at least 3.
NEXT : Write a Swift program to create a new array taking the first element from two given arrays of integers. If either array is length 0, ignore that array.

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.