标签:.net turn 操作 var apple 传值 href function sid
近期在用swift写代码,尽管遇到一些问题,可是代码量确实减了不少。
swfit新手教程系列会随着我使用swfit中的积累,不断地去修正更新
之前的教程
swift新手教程4-集合(Array,Dictionary)
在swift中,函数有keywordfunc声明func firstFunction()->Int{ var result = 4 return result } println(firstFunction())//调用參数为空,返回值为Int
func hwcFunction(){ println("Hello hwc") }
func hwcFunction(first:String,second:String)->String{ return first+second } println(hwcFunction("hello","hwc"))
func hwcSwapString(first:String,second:String)->(String,String){ return (second,first) } var (second,first) = hwcSwapString("first","second")
外部參数能够完美解决问题
我们来举个样例
func addPersonalInformation(Name:String,Sex:String)->String{ return Name+":"+Sex } addPersonalInformation("WenchenHuang","Male")
func addPersonalInformation(name Name:String,sex Sex:String)->String{ return Name+":"+Sex } addPersonalInformation(name:"WenchenHuang",sex:"Male")
func addPersonalInformation(#name:String,#sex:String)->String{ return name+":"+sex } addPersonalInformation(name:"WenchenHuang",sex:"Male")
func hwcPrint(toPrint:Int = 10){ println(toPrint) }
hwcPrint()//输出10 hwcPrint(toPrint:11)//输出11这里,我们不难看出,在调用的时候swift自己主动为我们生成了一个外部參数的名称
能够使用下划线作为默认參数的外币名称,这样swfit不会提供外部參数名称。但不建议这么做
func hwcPrint(toPrint:Int){ toPrint = toPrint+1//Wrong println(toPrint) } func hwcPrint(var toPrint:Int){ toPrint = toPrint+1//Right println(toPrint) }
func addMultiString(toPrint:String...)->String{ var resultString:String = "" for tempString in toPrint{ resultString+=tempString } return resultString } var result1 = addMultiString("hello","world") var result2 = addMultiString("Wen","chen","Huang")
这类參数传入原值得引用。函数内对传入參数的操作会改变原始值,传入引用的时候须要使用&
func addOne(inout input:Int){ ++input } var test1 = 10 addOne(&test1)//test1 = 11 func addOne(var input:Int){ ++input } var test2 = 10 addOne(test3)//test2 = 10
func addThree(addTwo:(Int,Int)->Int,thrid:Int)->Int{ return addTwo+thrid }
func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } func chooseStepFunction(backwards: Bool) -> (Int) -> Int { return backwards ?stepBackward : stepForward } let moveNearerToZero = chooseStepFunction(currentValue > 0)
func chooseStepFunction(backwards: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backwards ? stepBackward : stepForward }
myButton.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside) let timer = NSTimer(timeInterval: 1, target: self, selector: "test", userInfo: nil, repeats: false) func test{ //Do something } function buttonTapped(sendr:AnyObject){ //Do something }
Swift新手教程系列5-函数+selector在swift中的使用方法
标签:.net turn 操作 var apple 传值 href function sid
原文地址:http://www.cnblogs.com/yutingliuyl/p/6850390.html