Swift - Write program to find the index of the first occurrence of a character

Requirements

You have a string of characters and you want to find the index of the first occurrence of a character.

Hint

For example, in the string "This is a string," the index of the character "a" is 8.

Demo

P:You could solve this problem using the following code snippet:

Demo

var c :Character
var found = false
var index = 0/* w  ww. j av  a 2  s.  c o  m*/
for c in "This is a string" {
    if c != "a" && !found {
        index = index + 1
    } else {
        found = true
    }
}

print("Position of 'a' is \(index)")

Result