swift 闭包+嵌套函数+extension+单例+嵌套函数+??

时间:2022-08-02 05:56:06
 //: Playground - noun: a place where people can play

 import UIKit

 //*******************嵌套函数*****************************
func getMathFunc(type:String) -> ((Int) -> Int) {
func squre(num:Int) -> Int{
return num * num
}
func cube(num:Int) -> Int{
return num * num * num
}
switch (type) {
case "squre":
return squre
default:
return cube
}
} var mathFunc = getMathFunc("squre")
mathFunc()
var mathFunc2 = getMathFunc("other")
mathFunc2() //********************闭包****************************
// { (形参列表) -> 返回值类型 in
// 可执行表达式
// } func getMathFunc1(type:String) -> ((Int) -> Int) {
func squre(num:Int) -> Int{
return num * num
}
func cube(num:Int) -> Int{
return num * num * num
}
switch (type) {
case "squre":
return {(num:Int) -> Int in
return num * num
}
default:
return {(num:Int) -> Int in
return num * num * num
}
}
}
var maxFunc3 = getMathFunc("squre")
maxFunc3()
var maxFunc4 = getMathFunc("other")
maxFunc4() //
var squre: (Int) -> Int = {(num) in return num * num}
squre() //?? 如果??左边有值就就是原值,如果没有值那么就设置为??右边的值
var a:Int?
//a = 11
print(a ?? )
//: Playground - noun: a place where people can play

import UIKit
print("") // MARK - guard
func checkup(person:[String:String]){
guard let id = person["id"] else {
print("没有id,不能进入")
return
}
guard let exam = person["exam"] else{
print("没有exam,不能进入")
return
}
print("id:\(id),exam:\(exam)--批准进入")
}
//checkup(["id":"123"])
//checkup(["exam":"456"])
checkup(["id":"","exam":""]) //MARK - 熟悉观察
let MaxValue =
let MinValue = -
var number = {
willSet{
print("从\(number)变为\(newValue)")
}
didSet{
if number > MaxValue {
number = MaxValue
}else if number < MinValue{
number = MinValue
}
print("已经从\(oldValue)变为\(number)")
} }
number =
number //MARK - 扩展 extension
//对Int扩展,增加一个方法
extension Int {
func times(closure:(() -> ())?){
if self >= {
for _ in ..<self {
closure?()
}
}
}
}
.times{print("走起")}
//MARK 协议扩展
extension CustomStringConvertible{
var upperDescription:String{
return self.description.uppercaseString
}
}
["key":"value"].upperDescription //map:得到一个由闭包里面的返回值组成的新序列
//flatMap:与map类似的功能,但是会过滤掉返回值里面的nil值
//filter:得到一个由闭包返回值为true的值组成的新序列 var result = [,,,,].map{$ * }
result result = [,,,,].filter{$ > }
result //MARK 单例
class TestObject {
static let testObject = TestObject()
//私有构造,保证外部对象通过init方法创建单例类的其他实例
private init() { }
}

源码下载:https://github.com/pheromone/swift-extension-

http://download.csdn.net/detail/shaoting19910730/9515986