w3resource

Swift Array Programming Exercises: Test if two given arrays of integers have the same first or last element

Swift Array Programming: Exercise-3 with Solution

Write a Swift program to test if two given arrays of integers have the same first or last element. Both arrays length must be 1 or more.

Pictorial Presentation:

Swift Array Programming Exercises: Test if two given arrays of integers have the same first or last element

Sample Solution:

Swift Code:

func first_last(_ a: [Int], _ b: [Int]) -> Bool {
    guard a.count > 0, b.count > 0 else 
    {
        return false
    }
    
    if a.first == b.first || a.last == b.last
    {
        return true
    } 
    else
    {
        return false
    }
}
print(first_last([1, 2, 3], [5, 1]))
print(first_last([1, 2], [4, 2]))
print(first_last([1, 2, 3, 1], [-1, 3, 5]))

Sample Output:

false
true
false

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to check whether the first element and the last element of a given array of integers are equal.
Next: Write a Swift program to compute the sum of all the elements of a given an array of integers and length 4.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.