迅速.网址返回nil [英] Swift. URL returning nil

查看:498
本文介绍了迅速.网址返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的应用中打开网站,但是由于某种原因,一行总是返回nil,这是我的代码:

I am trying to open a website in my app, but for some reason one line keeps returning nil, heres my code:

let url = URL(string: "http://en.wikipedia.org/wiki/\(element.Name)")!
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url)
    }
}

这是不断返回此错误的第一行(let url = URL...):

It's the first line (let url = URL...) that keeps on returning this error:

致命错误:解开可选值时意外发现nil.

fatal error: unexpectedly found nil while unwrapping an Optional value.

该如何解决?

推荐答案

不要用(!)强制将其解包.当您使用(!)并且变量的值为nil时,您的程序崩溃并得到该错误.取而代之的是,您想使用警卫队让"或如果让"语句安全地打开可选项.

Don't force unwrap it with (!). When you use (!) and the value of the variable is nil, your program crashes and you get that error. Instead, you want to safely unwrap the optional with either a "guard let" or an "if let" statement.

guard let name = element.Name as? String else {
    print("something went wrong, element.Name can not be cast to String")
    return
}

if let url = URL(string: "http://en.wikipedia.org/wiki/\(name)") {
    UIApplication.shared.openURL(url)
} else {
    print("could not open url, it was nil")
}

如果这不能解决问题,则可能是element.Name存在问题.因此,如果您仍然遇到问题,我将检查是否接下来是可选步骤.

If that doesn't do the trick, you may have an issue with element.Name. So I would check to see if that's an optional next if you're still having issues.

更新

我添加了一种可能的方法来检查element.Name属性,以查看是否可以将其强制转换为String并创建要创建的所需url.您可以在我之前发布的代码上方看到该代码.

I added a possible way to check the element.Name property to see if you can cast it as a String and create the desired url you're looking to create. You can see the code above the code I previously posted.

这篇关于迅速.网址返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆