下面的例子定义了一个名为count函数,用它计来算字符串中基于标准的美式英语中设定使用的元音、辅音以及字符的数量:
复制代码
func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
var vowels = 0, consonants = 0, others = 0
for character in string {
switch String(character).lowercaseString {
case "a", "e", "i", "o", "u":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
++consonants
default:
++others
}
}
return (vowels, consonants, others)
}
您可以使用此计数函数来对任意字符串进行字符计数,并检索统计总数的元组三个指定Int值:
复制代码
let total = count("some arbitrary string!")
println("(total.vowels) vowels and (total.consonants) consonants")
// prints "6 vowels and 13 consonants"
需要注意的是在这一点上元组的成员不需要被命名在该该函数返回的元组中,因为他们的名字已经被指定为函数的返回类型的一部分。
3、函数参数名
所有上面的函数都为参数定义了参数名称:
复制代码
func someFunction(parameterName: Int) {
// function body goes here, and can use parameterName
// to refer to the argument value for that parameter
}
然而,这些参数名的仅能在函数本身的主体内使用,在调用函数时,不能使用。这些类型的参数名称被称为本地的参数,因为它们只适用于函数体中使用。
外部参数名
有时当你调用一个函数将每个参数进行命名是非常有用的,以表明你传递给函数的每个参数的目的。
如果你希望用户函数调用你的函数时提供参数名称,除了设置本地地的参数名称,也要为每个参数定义外部参数名称。你写一个外部参数名称在它所支持的本地参数名称之前,之间用一个空格来分隔:








