在 swift 中,函数的形参和返回值是非常具有灵活性的。你可以定义任何事情,无论是一个简单的仅有一个未命名形参的工具函数,还是那种具有丰富的参数名称和不同的形参选项的复杂函数。
多输入形参
多输入形参
1. func halfOpenRangeLength(start: Int,end: Int) -> Int { 2. return end - start 3. } 4. println(halfOpenRangeLength(1,10)) 5. // prints "9"
无形参函数
无形参函数
1. func sayHelloWorld() -> String { 2. return "hello,world" 3. } 4. println(sayHelloWorld()) 5. // prints "hello,world"
无返回值的函数
1. func sayGoodbye(personName: String) { 2. println("Goodbye,\(personName)!") 3. } 4. sayGoodbye("Dave") 5. // prints "Goodbye,Dave!"
多返回值函数
你可以使用一个元组类型作为函数的返回类型,来返回一个由多个值组成的复合返回值。
1. func count(string: String) -> (vowels: Int,consonants: Int,others: I nt) { 2. var vowels = 0,consonants = 0,others = 0 3. for character in string { 4. switch String(character).lowercaseString { 5. case "a","e","i","o","u": 6. ++vowels 7. case "b","c","d","f","g","h","j","k","l","m",8. "n","p","q","r","s","t","v","w","x","y","z": 9. ++consonants 10. default: 11. ++others 12. } 13. } 14. return (vowels,consonants,others) 15. }参考:《The Swift Programming Language中文完整版(CocoaChina精校)》