w3resource
swift Programming Exercises

Swift Array Programming Exercises: Check whether the first element and the last element of a given array of integers are equal

Swift Array Programming: Exercise-2 with Solution

Write a Swift program to check whether the first element and the last element of a given array of integers are equal. The array length must be 1 or more.

Pictorial Presentation:

Swift Array Programming Exercises: Check whether the first element and the last element of a given array of integers are equal

Sample Solution:

Swift Code:

func check_first_last(_ arra: [Int]) -> Bool {
    guard arra.count > 0 else 
    {
        return false
    }
    if arra.first == arra.last 
    {
        return true
    } else
    {
        return false
    }
}
print(check_first_last([1, 2, 3]))
print(check_first_last([1, 2, 3, 1]))
print(check_first_last([1, 2, 2, 1]))
print(check_first_last([1]))

Sample Output:

false
true
true
true

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to check if 5 appears as either the first or last element in a given array of integers.
Next: 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.

What is the difficulty level of this exercise?