码迷,mamicode.com
首页 > 编程语言 > 详细

SWIFT——函数

时间:2015-11-13 18:29:01      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

 1 func sayHello(personName:String) ->String             //返回是String类型
 2 {
 3        let greeting = "hello" + personName + "!"
 4        return greeting    
 5 }
 6 
 7 println(sayHello("lin"))                           //hello lin!
 8 
 9 func add(a:Int, b:Int) ->Int
10 {
11        return a + b                              
12 }
13 
14 println(add(20,30))                               //50
15 
16 func process() -> Float
17 {
18        return 3*20;
19 }
20 
21 println(process())                                 //60
22 
23 func method()
24 {
25        println("hello world")
26 }
27 method()                                           //hello world
28 
29 //返回超过一个值
30 func count(string:String) -> (vowels:Int, consonants:Int, others:Int)
31 {
32         var vowels = 0;
33         var consonants = 0;
34         var others = 0;
35         for c in string
36         {
37                switch String(c).lowercaseString
38                {
39                        case "a","e","i","o","u":
40                                ++vowels;                   //++后面不能有空格
41                        case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z":
42                                ++consonants
43                        default:
44                                ++others
45                 }
46          }
47          return (vowels, consonants,others)
48 }
49 
50 let total = count("some arbitrary string!")
51 println("\(total.vowels) vowels and \(total.consonants) consonants ") //6 vowels and 13 consonants

1、扩展参数名

 1 func process(p1:String, p2:Int) ->String
 2 {
 3         return "name:" + p1 + " age:" + String(p2)
 4 }
 5 println(process("bill",20))         //name:bill age:20
 6 
 7 func process1(name p1:String, age p2:Int) ->String
 8 {
 9          return "name:" + p1 + " age:" + String(p2)
10 }
11 println(process1(name:"Mike",age:17))     //name:Mike age:17.
//println(process1(age:17,name:"Mike") //这种会报错,说没发现name,所以这个顺序必须严格一致。

2、内部参数名和扩展参数名合二为一

1 func process2(#name:String, #age:Int) ->String
2 {
3      return "name:" + name + " age:" + String(age)  
4 }
5 println(process2(name:"BILL",age:30))

3、默认参数值

 1 func process3(name p1:String = "MIKE", age p2:Int = 30) ->String
 2 {
 3       reutrn "name:" + p1 + " age:" + String(p2)  
 4 }
 5 
 6 println(process3())
 7 println(process3(name:"JOHN"))
 8 
 9 func process4(name:String = "mike", age:Int = 30) ->String
10 {
11        return "name:" + name + " age:" + String(age)  
12 }
13 
14 println(process4(name:"..."))//前面虽然是用内部参数名定义的,但是由于后面的赋值操作,所以将内部参数隐式转为了外部参数,这里如果不加name:会报错。

4、可变参数

5、常量和变量参数

6、输入输出参数

7、函数类型

8、嵌套函数

 

SWIFT——函数

标签:

原文地址:http://www.cnblogs.com/zhuzhubjtu/p/4962818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!