//函数
//老规矩“hello world”敬上
//函数最多只有一个可变参数(strings)放在最后一个参数
func joinStr(seperator:Character=",",strings:String...)->String{
var result:String =""
for (index,element) in strings.enumerated() {
if index !=0 {
result.append(seperator)
}
result += element
}
return result
}
let result = joinStr(seperator:" ", strings:"Hello","world","!")
print(result)
//多层函数的嵌套
func fn()->(Int,Int)->Int{
func minus(a:Int,b:Int)->Int{
return a-b
}
returnminus;
}
let minus =fn()
print(minus(10,5))
func calculate(num1:Int,num2:Int,fn:(Int,Int)->Int)->Int{
return fn(num1,num2)
}
print(calculate(num1:1, num2:2, fn: minus))
//方法与UI结合 textField添加内容监听方法 方法写在 viewDidLoad之外//全局变量 写在class之外
let showLabel =UILabel.init()
let textField =UITextField.init(frame:CGRect.init(x:20, y: 80, width:120, height:30));
textField.keyboardType =UIKeyboardType.decimalPad
textField.borderStyle =UITextBorderStyle.roundedRect
textField.font =UIFont.systemFont(ofSize:15)
textField.textColor =UIColor.darkGray;
textField.placeholder ="请输入内容"
textField.addTarget(self, action:#selector(FuncViewController.textFieldDidChange), for: UIControlEvents.editingChanged)
view.addSubview(textField)
showLabel.frame =CGRect.init(x: textField1.frame.minX, y: textField2.frame.maxY+10, width: textField1.frame.width, height:textField1.frame.height)
showLabel.text ="输入的内容"
showLabel.font =UIFont.systemFont(ofSize:15)
showLabel.textColor =UIColor.lightGray
showLabel.textAlignment =NSTextAlignment.left
view.addSubview(showLabel)
func textFieldDidChange(textField:UITextField){
var filePath =String(#file)!
let paths:[String] = filePath.components(separatedBy:"/")
filePath = paths.last!
print("<"+filePath+" : "+String(#line)+"> "+String(textField.text!))
showLabel.text = textField.text
}
//闭包
//闭包就是函数代码块,对函数进行简化 隐藏return关键字 $0...$n表示第n个参数
let res =calculate(num1:1, num2:2, fn: {
$0-$1
})
print(res)
//闭包就是捕捉一定作用域的常量或者变量进而闭合并包裹着
func add(total:Int,step:Int)->()->Int{
var total = total
func fn()->Int{
total = total+step
return total
}
returnfn
}
let a =add(total:0, step:2)
print(a())
print(a())
/**可在方法前此声明,告诉编译器此方法可以不接收返回值 **/
@discardableResult