import Foundation
/*
c语言block的格式:
返回值类型(^block变量名)(参数类型1:参数1,参数类型2:参数2...){
代码段
return
}
*/
//swift闭包
//跟block一样,也是一种数据类型
//跟函数的区别也一样,没有名字
/*
闭包格式:
let/var闭包名={
(参数1:数据类型,参数2:数据类型...)->返回值类型
in
代码段
return
}
*/
//无参无返的闭包
/*
let闭包名= {
()->()
in
代码段
}
调用:闭包名()
*/
//定义
letclosure = {
()->()
in
println("hello,world")
}
//调用
closure()
//练习:
letclosure1 = {
(month:Int)->()
in
switchmonth{
caselettempwheretemp >=1&& temp <=3:
println("Summer")
caselettempwheretemp >=4&& temp <=6:
println("Summer")
caselettempwheretemp >=7&& temp <=9:
println("Autumn")
caselettempwheretemp >=10&& temp <=12:
println("Winter")
default:
println("stupid")
}
}
closure1(5)
//有参有返
//题目1:定义一个闭包,该闭包输入一个月份,返回对应的季节有返
letclosure3 = {
(month:Int)->(String)
in
switchmonth{
caselettempwheretemp >=1&& temp <=3:
return"Spring"
caselettempwheretemp >=4&& temp <=6:
return"Summer"
caselettempwheretemp >=7&& temp <=9:
return"Autumn"
caselettempwheretemp >=10&& temp <=12:
return"Winter"
default:
return"stupid"
}
}
closure1(7)
//定义一个闭包,该闭包传入一个字符串,闭包在该字符串后面拼接上“hello”,闭包返回新的字符串和新的字符串的长度(使用元组)
letclosure2 = {
(str:String)->(String,Int)
in
letnewString = str +"hello"
letlength = newString.lengthOfBytesUsingEncoding(4)
return(newString,length)
}
lettemp =closure2("lanou")
println(temp.0)
println(temp.1)
/*对比函数:
func hello(str:String)->(String,Int){
let newString = str + "hello"
let length = newString.lengthOfBytesUsingEncoding(4)
return (newString,length)
}
let temp = hello("lanou")
println(temp.0)
println(temp.1)
*/
网友评论