swift - 更新到 Swift 3 时出现明确指定的类型 'NSURL?' 问题

标签 swift swift3 nsurl

我在将我的 iOS 应用代码更新到最新版本的 Swift 时遇到问题。

我有一个函数:

public class func gifWithURL(gifUrl:String) -> UIImage? {
    // Validate URL
    guard let bundleURL:NSURL? = NSURL(string: gifUrl)
        else {
            print("SwiftGif: This image named \"\(gifUrl)\" does not exist")
            return nil
    }

    // Validate data
    guard let imageData = NSData(contentsOf: bundleURL! as URL) else {
        print("SwiftGif: Cannot turn image named \"\(gifUrl)\" into NSData")
        return nil
    }

    return gifWithData(data: imageData)
}

并且在以下行中收到警告:

guard let bundleURL:NSURL? = NSURL(string: gifUrl)

并收到警告:

Explicitly specified type 'NSURL?' adds an additional level of optional to the initializer, making the optional check always succeed

Xcode 允许我自动修复问题。当我执行此自动修复时,我的代码更改为:

guard let bundleURL:NSURL NSURL(string: gifUrl)

这显然不是正确的语法。

我不确定我需要添加/删除什么以使我的代码完全符合 Swift 3 标准并正常工作。

最佳答案

NSURL(string:) 将返回可选的 NSURL? 实例,您已经可以选择用 guard 包装它,所以删除 : NSURL? 因为你再次设置它 optional 而不是 non-optional 同样,在 Swift 3 中使用 native URLData而不是 NSURLNSData。整个代码就像这样。

guard let bundleURL = URL(string: gifUrl), let imageData = try? Data(contentsOf: bundleURL) else {
     print("SwiftGif: This image named \"\(gifUrl)\" does not exist")
     return nil
}
//Access the imageData here

注意: Data(contentsOf:)throw 异常,因此您需要使用 do try catch block 捕获它。

关于swift - 更新到 Swift 3 时出现明确指定的类型 'NSURL?' 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41520220/

相关文章:

ios - NSData dataWithContentsOfURL 用于相机胶卷中的 URL

ios - 尝试从我的应用程序打开其他应用程序时出现 Swift 错误 |操作无法完成。 (操作系统状态错误-10814。)

swift - Firebase 从多个位置检索数据(多个查询)

swift - 我有关于 tableView 的问题。滚动时值变化

ios - UIButton 选定的图像不起作用

ios - 调用的 Swift 结果未使用

ios - 应用程序更新、NSURL 和文档目录

json - 从 JSON Api 快速请求数据

ios - 仅适用于特别构建和较旧的设备,保存时核心数据崩溃

ios - 如何使用 PHAsset 从文件中获取 NSData