case .getFile: DispatchQueue.global().async { [weak self] in guard let weakSelf = self else { return } guard let fileId = params.first, fileId.count > 0 else { return } let localFileDataStr = weakSelf.getFileFromLocal(fileId: fileId) if localFileDataStr.count > 0 { weakSelf.h5ProRuntimeCallback(payload, id, data: "'\(localFileDataStr)'") return } weakSelf.getFileFromHiCloud(fileId: fileId) {[weak self] fileDataString, errorCode in guard let weakSelf = self else { return } weakSelf.h5ProRuntimeCallback(payload, id, data: "'\(fileDataString)'", error: errorCode) } } 这段代码怎么优化
时间: 2024-01-17 16:05:42 浏览: 116
这段代码可以进行以下优化:
1. 使用guard let来避免嵌套的if语句,使代码更加清晰易读。
2. 对于闭包中的self,使用weak self来避免循环引用问题。
3. 将多余的字符串拼接操作删除,直接传递原始数据即可。
4. 对于DispatchQueue.global().async方法,可以使用DispatchQueue.global(qos: .userInitiated).async来指定优先级。
优化后的代码如下:
```
case .getFile:
guard let fileId = params.first, !fileId.isEmpty else {
return
}
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
guard let weakSelf = self else {
return
}
let localFileDataStr = weakSelf.getFileFromLocal(fileId: fileId)
if !localFileDataStr.isEmpty {
weakSelf.h5ProRuntimeCallback(payload, id, data: localFileDataStr)
return
}
weakSelf.getFileFromHiCloud(fileId: fileId) { [weak self] fileDataString, errorCode in
guard let weakSelf = self else {
return
}
weakSelf.h5ProRuntimeCallback(payload, id, data: fileDataString, error: errorCode)
}
}
}
```
阅读全文