Swift学习笔记-函数
2018-10-22 本文已影响4人
土豆吞噬者
最简单的函数
func printHello()
{
print("hello world")
}
printHello()
带参数的函数
func printHelloWithName(name:String)
{
print("hello \(name)")
}
printHelloWithName(name: "xy")
外部参数
swift中参数名可以填两个,前者是外部参数名(调用者使用),后者是内部参数名(函数内部使用)
//使用_省略外部参数
func printHelloWithName(_ name:String)
{
print("hello \(name)")
}
//使用外部参数to
func printHello(to name:String)
{
print("hello \(name)")
}
printHello(to:"XiaoMing")
变长参数
变长参数接受0个或者更多输入值作为实参,函数只能有一个变长参数,而且一般是最后一个
func printHellos(to names:String...)
{
for name in names {
print("hello \(name)")
}
}
printHellos(to:"LiLei","XiaoHong","xy")
默认参数值
用法与C/C++类似,就不介绍了
func printHelloWithCaller(name:String,caller:String="xy")
{
print("\(caller) say hello to \(name)")
}
//xy say hello to XiaoMing
printHelloWithCaller(name: "XiaoMing")
//XiaoHong say hello to XiaoMing
printHelloWithCaller(name: "XiaoMing",caller: "XiaoHong")
inout参数
inout参数能让函数影响函数体以外的变量,inout参数不能有默认值,变长参数不能标记为inout
func getErrorStr(errorCode:Int,str:inout String)
{
str+="(\(errorCode))"
print(str)
}
var errStr="Not Found"
//Not Found(404)
getErrorStr(errorCode: 404, str: &errStr)
返回值
在函数后面添加->返回值类型即可
func getErrorStr(errorCode:Int,str:inout String)->String
{
str+="(\(errorCode))"
return str
}
var errStr="Not Found"
print(getErrorStr(errorCode: 404, str: &errStr))
无返回值的函数也可以这样写
func printHello()->Void
{
print("hello world")
}
使用元组可以返回多个值
func getErrorInfo()->(errorStr:String,errorCode:Int)
{
return ("Not Found",404)
}
func getErrorInfo()->(String,Int)
{
return ("Not Found",404)
}
print(getErrorInfo())
当返回值有可能为nil时使用可空类型
func getErrorStr(code:Int)->String?
{
if code==200{
return nil
}else{
return "error"
}
}
print(getErrorStr(code:200))
print(getErrorStr(code:400))
嵌套函数
嵌套函数在另一个函数内部声明并实现,它在函数外部不可用,且它能访问函数作用域内的所有数据
func getResult(a:Int,b:Int)->Int
{
let x=a+b
func subFunc()->Int
{
return a*b+x
}
return subFunc()
}
print(getResult(a: 10, b: 20))//230
guard
guard语句与if语句很相似,不过更加简洁,可读性更强,主要用于在函数开头判断条件,不满足的时候提前退出函数
func printCode(code:Int)
{
guard code==200 else {
print("error")
return
}
print("ok")
}
printCode(code:404)
函数类型
函数类型由参数类型和返回值类型组成,表示为(参数类型...)->(返回值类型...),通过函数类型可以把函数作为参数和返回值使用
func printCode(code:Int)->String
{
return "code is \(code)"
}
//定义函数类型
let printCodeFunc:(Int)->(String)=printCode
//无须填写参数名
print(printCodeFunc(404))