微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift中函数的形参和返回值

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精校)》

原文地址:https://www.jb51.cc/swift/325472.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐