import UIKit
var str = "Hello, playground"
//1.1闭包,与oc中的block类似
//方法声明: (参数) -> 返回值 {函数体}
//闭包声明:{(参数) -> 返回值 in 函数体}
//可以在代码中使用或者用来作为参数传值。
let names = [5,2,10,23,4]
let namesSort = names.sorted { (int1,int2) ->Bool in
return int1 > int2
}
print(namesSort)
//上面等同于下面
func sortMthod(num1:Int, num2:Int)-> Bool{
return num1 > num2
}
print(names.sorted(by: sortMthod))
//1.2 可以隐式的返回
//隐式就类似于limbda表达式
//单行表示闭包,可以通过隐藏return关键字来隐式返回单行表达式结果
let hiddenSort = names.sorted{ num1,num2 -> Bool in num1 > num2}
print("隐式:\(hiddenSort)")
//1.3 参数名称缩写
//直接通过 $0,$1来顺序调用闭包的参数
//省略了in关键字
let nameSortFive = names.sorted(){
return $0 < $1
}
let nameSortsix = names.sorted{$0 < $1}
print("参数名称缩写:\(nameSortFive), \(nameSortsix)")
//swift可以推断参数和返回值的类型,因此基本类型并不需要作为闭包表达式定义中的一部分
//有的类型都可以被直接推断,返回箭头->和参数也可以省略
//1.4尾随闭包 增强函数的可读性
//当函数的最后一个参数是闭包,可以将闭包放在方法名后面
_ = names.sorted() { (int1,int2) ->Bool in
return int1 > int2
}
// ()->() 函数类型 无参数 无返回值
func TestMethod(bibaoMethod:()->()){
bibaoMethod()
print("接收闭包数据")
}
TestMethod(bibaoMethod: {
print("闭包正规写法")
})
TestMethod() {
print("闭包尾随写法")
}
//如果函数只想要闭包表达式一个参数,当使用尾随方式时候
//可以把()省略
TestMethod {
print("闭包尾随简写")
}
//oc block有内存泄露,闭包也存在这个问题
//使用weak释放
//2.1 枚举
enum CompassPoint{
//oc默认枚举成员赋值 0 , 1, 2 ... swift没有默认赋值
case North, N //多个用,隔开
case South
case East
case West
}
print(CompassPoint.North)
//枚举赋值
var direction = CompassPoint.North
direction = .East // 不需要枚举,直接 . 加上枚举类型,可以推断出来
//2.2 相关值绑定
enum Barcode{
case NumberCodes(Int, Int)
case StringCodes(String)
}
var productBarcode = Barcode.NumberCodes(122, 1233453)
var productStringcode = Barcode.StringCodes("小米")
switch productBarcode {
case .NumberCodes(let system,let ident):
print("数字条形码:系统编号\(system) 物品提示:\(ident)")
case .StringCodes(let code):
print("sdfsfsdf\(code)")
}
//2.3 原始值rawValue(带有默认值)
enum Month: Int {
case January = 1
case February
case March
case April
case May
case June
case July
case August
case September
case October
case November
case December
}
let value = Month.February
//rawValue是原始值,即
switch value {
case .January:
print("一月 \(value.rawValue)") //rawValue为1
case .February:
print("二月 \(value.rawValue)")
case .March:
print("三月 \(value.rawValue)")
case .April:
print("四月 \(value.rawValue)")
case .May:
print("五月 \(value.rawValue)")
case .June:
print("六月 \(value.rawValue)")
case .July:
print("七月 \(value.rawValue)")
case .August:
print("八月 \(value.rawValue)")
case .September:
print("九月 \(value.rawValue)")
case .October:
print("十月 \(value.rawValue)")
case .November:
print("十一月 \(value.rawValue)")
case .December:
print("十二月 \(value.rawValue)")
default:
print("------")
}
swif4基础学习(4)- 闭包、枚举
猜你喜欢
转载自blog.csdn.net/a1034386099/article/details/88845878
今日推荐
周排行