Swift 的 func,在传递参数的过程,如何排除 空值 blank?这是我在 Udacity 的 Swift Problem Set 中的一道作业题目。

Swift Problem Set 中的第16道题目如下:

Exercise 16

The function ‘beginsWithVowel’ should take a single ‘String’ parameter and return a ‘Bool’ indicating whether the input string begins with a vowel. If the input string begins with a vowel return true, otherwise return false.
First, you will want to test if the input string is “”. If the input string is “”, then return false. Otherwise, you can access the first character of a ‘String’ by using ‘nameOfString.characters[nameOfString.startIndex]’.

输入一个单词,如果单词开头为元音(A, E, I, O, U),则返回 Bool类型 为 true;如果单词开头为辅音,则返回 Bool类型 为 false;如果参数为 “” 空值,返回为false。

以下是检验样例:

beginsWithVowel(letter: "Apples")         // true
beginsWithVowel(letter: "pIG")             // false
beginsWithVowel(letter: "oink")            // true
beginsWithVowel(letter: "udacity")        // true

//Test if the input string is "". If the input string is "", then return false.
beginsWithVowel(letter: "")                  // false

最先想到的就是用:

if letter == nil

但是,Xcode 编译器提示了警告,非选择性比较字符串的值为nil始终返回false。

先来试试,

if letter == “”

既然 Swift 不允许 if letter == “”,那就从反面出发:

if letter != “”

用 if-else 语句,用 else 来否定 blank:

此方法在 Udacity 上的审阅评价:

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Next Post

Swift3获取系统系统间并比较

周六 5 月 6 , 2017
在 Swift3.x 版本中一个很不错的简化,就是 […]

更多文章