首页 > 解决方案 > 使用三元运算符重构

问题描述

这是我的代码,它实际上按我的预期工作:

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()?

标签: swiftif-statementmethods

解决方案


首先,应用于字符串的字符串插值是多余的。

如果要写入数据(一次),具体取决于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
}

推荐阅读