Swift 3.0 转换错误

Swift 3.0 converting error

我已将 Swift 2.2 代码转换为 Swift 3.0,但出现以下错误。

open func saveToPath(_ path: String, format: ImageFormat, compressionQuality: Double) -> Bool
{
    if let image = getChartImage(transparent: format != .jpeg) {
        var imageData: Data!
        switch (format)
        {
        case .png:
            imageData = NSUIImagePNGRepresentation(image)
            break

        case .jpeg:
            imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality))
            break
        }

        let url = NSURL(string: path)
        return imageData.write(to: url as! URL, options: true)
    }
    return false
}

错误:

Cannot convert value of type 'Bool' to expected argument type 'data.writeOptions' (aka 'NSData.writingOptions'))

这段代码有什么问题?

以下两行需要修复:

let url = NSURL(string: path)
return imageData.write(to: url as! URL, options: true)
  1. 使用 URL,而不是 NSURL
  2. 使用正确的初始化程序将文件路径字符串转换为文件 URL。
  3. 将正确的值传递给 options 参数。

固定代码应该是这样的:

let url = URL(fileURLWithPath: path)
return imageData.write(to: url, options: .atomic)