码迷,mamicode.com
首页 > 其他好文 > 详细

Swift 函数

时间:2014-07-26 00:17:16      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   for   re   c   

Swift函数以关键字func 标示。返回类型->

func GetName(strName:String)-> String
{
    return "for " + strName
}
let name = GetName("xx")
println("\(name)")

函数参数默认为let类型的。如果你想更改参数副本,那么你要显示使用var修饰。如果你像更改参数作为输入输出用inout,调用时候要用取地址符号&

func GetName(var strName:String)-> String
{
    strName += " hello"
    return "for " + strName
}
let name = GetName("xx")
println("\(name)")
func GetName(inout strName:String)
{
    strName += " hello"
    
}
var strTest = "oo"
GetName(&strTest)
println("\(strTest)")

函数类型:由函数参数类型与顺序以及函数返回值类型

func(iAge:Int, strName:String)->String
{ 
   return "KO"
}
//该函数类型可以记为:(Int, String)->String

在 swift 中您可以像任何其他类型一样的使用函数类型。例如,你可以定义一个常量或变量 为一个函数类型,并为变量指定一个对应函数

func AddTwoInts(a: Int, b: Int) -> Int { 
 return a + b
 }

var AddFunction:(Int, Int)->Int = AddTwoInts
这样你可以用AddFuncton调用方法,其实有点类似与AddFunction是函数AddTwoInts的名字变量
var iRes = AddFunction(1, 4)
同其他变量一样,它还支持类型推断

let AnotherMathFunction = AddTwoInts

 var iOther = AnotherMathFunction(5, 6)

 

函数类型可以作为函数参数使用

func PrintMathResult(MathFunction: (Int, Int) -> Int, a: Int, b: Int)
{
2. println("Result: \(MathFunction(a, b))") 3. }
4. PrintMathResult(AddTwoInts, 3, 5)

函数类型也可以作为返回类型

func FunctionTest(a:Int, b:Int)->(Int, Int) -> Int{
}

 

 

 

 

Swift 函数,布布扣,bubuko.com

Swift 函数

标签:style   blog   color   使用   io   for   re   c   

原文地址:http://www.cnblogs.com/zhidao-chen/p/3868411.html

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