You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift代码报错:无法将URL类型转换为预期的Bool类型

Fixing "Cannot convert value of type 'URL' to expected argument type 'Bool'" in Swift

Hey there, let's break down this error and get your image-saving code working properly!

What's Causing the Error?

The root issue is that you added try! before calling FileManager.default.url(...)—but this method does not throw errors at all.

try! is only meant for functions marked with throws (functions that can fail and throw an error). When you slap try! in front of a non-throwing function that returns a URL, the Swift compiler gets confused. It tries to interpret this as a boolean condition (since try! expects a throwable expression), hence the weird type mismatch error about converting URL to Bool.

Quick Fix for the Main Error

Just remove the unnecessary try! from that line. The url(for:in:appropriateFor:create:) method safely returns a URL without throwing, so no error handling is needed here:

let document = FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

Bonus: Fixing Other Potential Issues in Your Code

While we're at it, let's clean up a few other things that could cause crashes or unexpected behavior:

  • Incorrect isDirectory parameter: When appending the image filename, you set isDirectory: true—but 1.jpg is a file, not a directory. You can either set it to false or omit the parameter entirely (it defaults to false):

    let imgUrl = document.appendingPathComponent("1.jpg")
    
  • Risky force unwraps: Using ! to unwrap UIImage(named: "1.jpg") and UIImageJPEGRepresentation(...) can crash your app if the image doesn't exist or the conversion fails. Use a guard statement to handle these optionals safely:

    guard let image = UIImage(named: "1.jpg"), let imageData = UIImageJPEGRepresentation(image, 0.8) else {
        print("Failed to load image or convert to JPEG data")
        return
    }
    
  • Backwards file existence check: Your original code only writes the image if the file already exists—this is probably the opposite of what you want. If you want to create the image (or overwrite it), you can skip the fileExists check entirely and just write the data.

Full Corrected Code

Here's the cleaned-up version of your function with all fixes applied:

private func saveImages() {
    // Get the documents directory URL (no try! needed)
    let document = FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    print(document)
    
    // Create the full URL for our image file
    let imgUrl = document.appendingPathComponent("1.jpg")
    print(imgUrl.path)
    
    // Safely load the image and convert to JPEG data
    guard let image = UIImage(named: "1.jpg"), let imageData = UIImageJPEGRepresentation(image, 0.8) else {
        print("Could not load image or convert to JPEG data")
        return
    }
    
    // Write the image data to disk
    do {
        try imageData.write(to: imgUrl)
        print("image added successfully")
    } catch {
        print("image not added: \(error.localizedDescription)")
    }
}

内容的提问来源于stack exchange,提问作者sailendra muduli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:17:53