Swift基础学习(函数)

2016-08-01  本文已影响17人  whbsspu

函数结构

func 函数名(参数)-> 函数返回类型{
   函数体
}

函数类型

func halfOpenRangeLength(start: Int, end: Int) -> Int {
return end - start
}
println(halfOpenRangeLength(1, 10))
// prints "9"
func sayHelloWorld() -> String {
return "hello, world"
}
println(sayHelloWorld())
// prints "hello, world"
func sayGoodbye(personName: String) {
println("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"
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)
}

外部参数名

func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
return s1 + joiner + s2
}

join(string: "hello", toString: "world", withJoiner: ", ")
// returns "hello, world"

如果一个入参既是内部参数又是外部参数,那么只要在函数定义时参数前加#前缀即可。

可变参数

当传入的参数个数不确定时,可以使用可以参数,只需要在参数的类型名称后加上点字符(...)。

func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8, 19)
// returns 10.0, which is the arithmetic mean of these three numbers

注意:函数最多有一个可变参数的参数,而且必须出现在参数列表的最后以避免多参数调用时出现歧义。

输入输出参数

如果想用一个函数来修改参数的值,并且只在函数调用结束之后修改,则可以使用输入-输出参数。只要才参数定义时添加inout关键字即可表明是输入输出参数。

上一篇 下一篇

猜你喜欢

热点阅读