首页 > 代码库 > Swift基础之函数定义

Swift基础之函数定义

1. 方式和之前一样

2. 代码

 1 // 2 //  ViewController.swift 3 //  SwiftLesson3 4 // 5 //  Created by 薛雨仑 on 14-10-2. 6 //  Copyright (c) 2014年 Dylan. All rights reserved. 7 // 8  9 import UIKit10 11 class ViewController: UIViewController {12 13     override func viewDidLoad() {14         super.viewDidLoad()15         16         println(self.sum(1, num2: 2))17         18         println(self.sum_6(number: 1, number1: 2))19         println(self.sum_7(num1: 1, num2: 3))20         21     }22 23     override func didReceiveMemoryWarning() {24         super.didReceiveMemoryWarning()25     }26     27     // func28     29     func sum(num1: Int, num2: Int) ->Int {30         return num1 + num231     }32     33     // 定义返回值为void的函数的3种办法34     func sum_1 (num: Int) {35         36     }37     38     func sum_2 (num: Int) ->() {39         40     }41     42     func sum_3 (num: Int) ->Void {43         44     }45     46     // 无参数 注意不能省略参数括号47     func sum_4 () ->Int {48         return 1;49     }50     51     // 返回元组52     func sum_5 (Num: Int) ->(name: String, age:Int) {53         return ("Alice", 24)54     }55     56     // 外部参数名称57     func sum_6 (number num:Int, number1 num2:Int) ->Int {58         return num + num259     }60     61     // 使用# 简化外部参数62     func sum_7 (#num1:Int, num2:Int) ->Int {63         return num1 + num264     }65     66     // 函数默认参数67     func sum_8 (#num:Int, name:String = "Alice") ->String {68         return name + String(num)69     }70     71     // 在带有默认参数值的参数名前加个下划线 _ ,调用函数时就不用写外部参数名72     func sum_9 (#num:Int, _ name:String = "Alice") ->String {73         return name + String(num)74     }75     76     // append77     func sum_10 (var name:String = "Alice", strings:String, count:Int) ->String {78         for i in 0 ... count {79             name += "Dylan"80         }81         return name82     }83     84     85 }

 

Swift基础之函数定义