swift - 使用三元运算符重构
问题描述
这是我的代码,它实际上按我的预期工作:
static func imageName(for page: Int, isThumbnail: Bool) -> String {
return isThumbnail ? "\(page)_thumb.jpg" : "\(page).jpg"
}
static func writeImageFile(with data: Data, issue: Issue, page: Int) throws -> URL {
let path = MediaFileManager.issueImagesDirectoryURL(issue: issue)
let imagePath = path.appendingPathComponent("\(imageName(for: page, isThumbnail: false))")
let thumbPath = path.appendingPathComponent("\(imageName(for: page, isThumbnail: true))")
try data.write(to: imagePath)
try data.write(to: thumbPath)
return path
}
我想要相同的结果: - 创建 2 个附加到主路径的不同常量 - 将 2 个数据写入这 2 个路径
是否可以重构 writeImageFile()?
解决方案
首先,应用于字符串的字符串插值是多余的。
如果要写入数据(一次),具体取决于isThumbnail
您必须将其添加为参数
static func writeImageFile(with data: Data, issue: Issue, page: Int, isThumbnail: Bool) throws -> URL {
let url = MediaFileManager.issueImagesDirectoryURL(issue: issue)
let imageURL = url.appendingPathComponent(imageName(for: page, isThumbnail: isThumbnail))
try data.write(to: imageURL)
return url
}
推荐阅读
- node.js - 从 Digital Ocean Ubuntu Droplet 连接到 Mongo Atlas
- java - libgdx 控制器轴四舍五入到 1 或 -1
- c# - 遥测初始化程序从 .net 核心 MVC 应用程序添加请求正文内容以请求遥测属性不起作用
- amazon-web-services - 响应时间 API 网关和 Lambda
- java - 过去 X 分钟的 Kafka 实时平均值
- java - 文件正在运行不同的主
- json - 使用 JSON.net 进行 Dotliquid JSON 转换
- python - 正则表达式向后和向前看
- python - 在 Pandas df 上进行双重 for 循环
- jointjs - JointJS - 在列表中的 Inspector 中使用“when:”