最近在用swift写代码,虽然遇到一些问题,但是代码量确实减了不少。
swfit入门教程系列会随着我使用swfit中的积累,不断地去修正更新
之前的教程
swift单例模式详解-线程安全,多核性能
swift入门教程4-集合(Array,Dictionary)
swift入门教程3-字符串String
swift入门教程2-运算符
swift入门教程1-准备知识
在swift中,函数有关键字func声明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 }