Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Swift Basic Programming Exercise: Test if the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere

Swift Basic Programming: Exercise-24 with Solution

Write a Swift program to test if the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere.

Pictorial Presentation:

Swift Basic Programming Exercise: Test if the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere.

Sample Solution:

Swift Code:

func array012(_ input: [Int]) -> Bool {
        for (index, number) in input.enumerated() {
        let third_Index = index + 2
        let second_Index = index + 1
        
        if second_Index < input.endIndex && number == 1 && input[second_Index] == 2 && input[third_Index] == 3 {
            return true
        }
    }
    return false
}

print(array012([0, 1, 1, 2, 3, 1]))
print(array012([0, 1, 1, 2, 4, 1]))
print(array012([1, 1, 2, 0, 1, 2, 3]))

Sample Output:

true
false
true

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to check if one of the first 4 elements in a given array of integers is a 7. The length of the array may be less than 4.
Next: Write a Swift program to create a new string where all the character "a" have been removed except the first and last positions.

What is the difficulty level of this exercise?