//c
//int sum(int a, int b)
//oc
//-(int) sum:(int)a:(int)b
//Swift
//func 函数名(参数列表)->返回值的类型
//{
//代码块
//return 返回值
//}
funcsum(a:Int,b:Int) ->Int
{
lettoal = a + b
returntoal
}
//常见的函数类型
//没有参数,没有返回值
funcabout() ->Void
{
print("iphone Xs Max")
}
funcabout1() -> ()
{
print("iphone Xs Max")
}
//最常用
funcabout2()
{
print("iphone Xs Max")
}
about()
about1()
about2()
//有参数 没有返回值
funccallPhone(phoneNumber:String)
{
print("打电话给\(phoneNumber)")
}
callPhone(phoneNumber: "188888888888888888")
//没有参数 有返回值
funcreadMessage() ->String
{
return "这是一条来自10086的短信"
}
letmessage =readMessage()
print(message)
//有参数 有返回值
lettoal =sum(a:10, b:20)
print(toal)
//返回值是复杂类型
importFoundation
functirple(info:String) -> (name:String, age:Int)
{
letinfos = info.components(separatedBy:",")
return(infos[0],Int(infos[1])!)
}
let p = tirple(info: "zhangsan,20")
p.name
p.age
//使用注意
funcsay(info:String)
{
//info = "2018-9-29"
print("传入的信息为:\(info)")
}
say(info:"今天周六,要补课")
//形式参数问题
funcminus(num1:Int, num2:Int) ->Int
{
returnnum1 - num2//参数名
}
minus(num1:30, num2:20)//参数标签
funcmulti(_num1:Int,_num2:Int) ->Int
{
returnnum1 * num2//参数名
}
multi(30, 20)//参数标签
//默认参数问题
funcmakeCoffee(type:String="卡布奇诺") ->String
{
return "您点了一杯拿铁\(type)咖啡"
}
makeCoffee(type: "拿铁")
makeCoffee()
//可变函数10.9
functotal(numbers:Int...) ->Int
{
varsum =0
//numbers是什么类型
fornumberinnumbers
{
sum += number
}
returnsum
}
total()
total(numbers:10)
total(numbers:10,20)
total(numbers:10,20,30,40,50)
//inout 接受的事变量传过的地址
funcswapInt(a:inoutInt, b:inoutInt)
{
lettmp = a
a = b
b = tmp
}
vara =10
varb =20
print("交换之前: a=\(a),b=\(b)")
swapInt(a: &a, b: &b)
print("交换之后: a=\(a),b=\(b)")
//函数是个引用类型
funcsumInt(a:Int, b:Int) ->Int
{
lettoal = a + b
returntoal
}
funcmultiplyInt(a:Int,b:Int) ->Int
{
letresult = a * b
returnresult
}
varfuncV:(Int,Int) ->Int=sumInt
funcV(10,10)
funcV = multiplyInt
funcV(10,10)
//函数的参数是函数
funcprintResult(a:Int,b:Int,c:(Int,Int) ->Int) ->Int
{
letd = c(a,b)
return d
}
printResult(a: 10, b: 10, c: sumInt)
printResult(a: 10, b: 10, c: multiplyInt)
//函数的返回值的函数
funcgetResult(a:Int) -> (Int,Int) ->Int
{
ifa >0
{
returnsumInt
}
else{
return multiplyInt
}
}
letfuncl =getResult(a:-10)
funcl(10,20)
getResult(a: 10)(10,20)
网友评论