Swift学习06

函数
OC中的函数分为:无参无返回值,无参有返回值,有参无返回值,有参有返回值,共四种.Swift中的函数与OC中不同的是,OC中函数返回值只能为一个,而在Swift中,由于有元组数据类型,返回值可以是一个或多个.Swift比OC的函数多了inout函数类型,并且Swift支持函数的嵌套
// 无参无返回值函数
// 关键字 函数名(参数列表) -> 返回值类型
func test() -> Void{
print("我是第一个函数")
}
// 函数调用
test()


// 无参有返回值
func test1() -> String{
return "我是第二个函数,无参有返回值"
}
// 接收函数的返回值
let str = test1()
print(str)

print(test1())

// 返回一个Int类型数组
func test2() -> Array<Int>{
return [1, 2, 3]
}
print("我是第三个函数,无参有多个返回值",test2())

// 返回一个OC的数组
func test3() -> NSArray{
return [1, 2, "a", "b"]
}
print(test3())


// 有参无返回值的函数
// 参数格式: 参数名 : 参数类型
func test4(name : String, sex : String){ // -> Void 可以省略
print("我叫\(name),性别是\(sex)");
}
test4("罗峰", sex: "未知")

// 参数为数组: 参数名 : Array<数据类型>
func test5(array : Array<Int>){
print(array)
}
test5([1, 2, 3]);


// 有参有返回值
func test6(a : Int, b : Int) -> Int{
return a + b
}
print(test6(2, b: 3))

func test7(dic : Dictionary<Int, String>) -> Dictionary<Int, String>{
let dict = dic
return dict
}
print(test7([0 : "a"]))


// 无参有多个返回值
func test8() -> (String, String){
return ("罗峰", "18")
}
let type = test8()
print(type)
print(type.1)


// 有参有多个返回值
func test9(a : Int,b : String) -> (Int, String){
return (a, b)
}
print(test9(1, b: "a"))


// inout函数
// Swift函数里面的参数 默认是使用let修饰的, 是不可更改的
func test10(inout number : Int){
number = 100
}
var a = 5
test10(&a)
print(a)
// inout 在交换两个变量的值得时候 很好用


// 函数嵌套
// 第一层
func test11(){
// 第二层
// Swift可以在函数内部 定义新的函数
func test12(){

}
}

posted on 2016-03-01 09:19  caryt  阅读(105)  评论(0)    收藏  举报

导航