as 类型转换 向上转换
// NSIndexPath 转 IndexPath
NSIndexPath(row: 0, section: 0) as IndexPath
// String 转 NString
let str: String = "abc"
let str1 = (str as NSString).substring(to: 2)
print(type(of: str) ,str1, str.count) // String ab 3
使用as? 进行向下转型操作;转换成功为可选类型, 转换失败nil
let dict: [String: Any] = ["age":10,"a":2]
let age = dict["age"] as? Int
// age = (Int?)10 可选类型
let age1 = dict["age"] as? String
// age = (String)nil 可选类型
// 实例1
if let resultArray = response.resBody as? [[String: Any]], !resultArray.isEmpty, let reaultDictionary = resultArray.first, let itemDictionary = reaultDictionary["sematterList"] {
let modelArray = Mapper<XXAgedAreaModel>().mapArray(JSONObject: itemDictionary) ?? []
let sectionModel = weakSelf.dataSource.first
sectionModel?.models = modelArray
}
}
// 实例2
applist 定义为MBApplySubModel 类型
if let list = dataSource?[indexPath.row].applist as? [MBApplySubModel] {
vc.dataSource = list
}
as! 功能同as? 转换失败crash
// 定义的就是XXCreoleHealthCell
let homeCell = collectionView.dequeueReusableCell(withReuseIdentifier: XXCreoleHealthCell.identifier, for: indexPath) as! XXCreoleHealthCell
let model = ApplyModel.applist[indexPath.row]
self.ApplyTableViewCell(model: model as! MBApplySubModel)
if let model = ApplyModel.applist[indexPath.row] as? MBApplySubModel {
self.ApplyTableViewCell(model: model)
}
闭包 @escaping逃逸闭包 非逃逸闭包
// 非逃逸闭包、逃逸闭包,一般都是当做参数传递给函数
// 非逃逸闭包:闭包调用发生在函数结束前,闭包调用在函数作用域内
// 逃逸闭包: 闭包有可能在函数结束后调用,闭包调用逃离了函数作用域,需要通过@escaping声明
// 声明闭包参数字典,没有返回值
typealias XXGovpayCompletion = ([String: Any]) -> Void
// 封装网络请求
private static func requestAndOpenGovpay(classCode: String, method: String, fromViewController: UIViewController, completion: @escaping XXGovpayCompletion) {
let parameters = ["Email" : "xiaoming@126.com", "Vno" : "2" ]
let requestModel: HttpRequestModel = HttpRequestModel()
requestModel.parames = parameters
completion([:])
// 非逃逸闭包: 闭包回调写在这, 函数体没有执行完毕, 参数completion: XXGovpayCompletion 前面不需要添加 @escaping
fromViewController.showHUD()
HttpService.request(requestModel) { [weak fromViewController] (response, error) in
fromViewController?.hideHUD()
if response.isSuccess(), let resultBody = response.resBody as? [String : Any], let url = resultBody["url"] as? String, let sourceViewController = fromViewController?.navigationController{
let userInfo: [String : Any] = ["url" : url,
"loadType" : "2",
"parameters" : resultBody,
"navigationVC" : sourceViewController,
"closeImageName" : "closeWeb"]
URLRouter.openURL(ModulePayURL, withUserInfo: userInfo)
// completion([:])
// 逃逸闭包: 闭包回调写在这, 函数体已经全部执行完毕, 参数completion: XXGovpayCompletion 千面需要添加 @escaping
} else {
fromViewController?.showToast(withText: response.errormsg)
}
}
}
网友评论