-2

I want to test if the input string is "". If the input string is "", then return false.

 var x = ""
 func beginsWithVowel(x: String) -> Bool {
    if x.characters[x.startIndex] == "a" || x.characters[x.startIndex] == "A"{
        return true
    }else if x.characters[x.startIndex] == "e" || x.characters[x.startIndex] == "E"{
        return true
    }else if x.characters[x.startIndex] == "i" || x.characters[x.startIndex] == "I"{
        return true
    }else if x.characters[x.startIndex] == "o" || x.characters[x.startIndex] == "O"{
        return true
    }else if x.characters[x.startIndex] == "u" || x.characters[x.startIndex] == "U"{
        return true
    }else {
    return false
    }
}

beginsWithVowel(x: x)

But I got a error: fatal error: Can't form a Character from an empty String. How can i fix it? Thank You. P.S. cant use optional string and the problem wan't how to check empty string, but why it cant return bool in function.

  • I'd check first if x is empty (before checking if it's A, E, etc), so no method would be applied to an empty string ('.characters' seems to cast x to a Character, so it might be throwing an exception there). – Alfabravo Jun 01 '17 at 19:59

2 Answers2

1

You can use guard to make sure your string has the first character and you can use an array with your vowels and check if it contains the first character.

func beginsWithVowel(x: String) -> Bool {
    guard let first = x.characters.first else { return false }
    return ["a","e","i","o","u","A","E","I","O","U"].contains(first)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    You can simplify that to `.contains(first)` since Swift will then infer the literal array to be `[Character]`. – vacawama Jun 01 '17 at 20:09
0

Make the empty check first

func beginsWithVowel(x: String) -> Bool {
    if x.isEmpty { return false }
    if x.characters[x.startIndex] == "a" { ...

Slightly different approach using regular expression, it includes the empty check:

func beginsWithVowel(x: String) -> Bool {
    let regex = try! NSRegularExpression(pattern: "^[aeiou]", options: .caseInsensitive)
    return regex.firstMatch(in: x, range: NSMakeRange(0, x.utf16.count)) != nil
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • why make the empty check first can fix it? is there any principle? – Chun Yeung Jun 01 '17 at 20:23
  • Because if it passes the test it's guaranteed that there is at least one character in the string. The error occurs if there is no character at `startIndex`. Btw: Retrieving the first character 10 times with this syntax is very inefficient. – vadian Jun 01 '17 at 20:24