将String转换为URL(为什么结果变量为nil) [英] Convert String to URL (Why is resulting variable nil)

查看:293
本文介绍了将String转换为URL(为什么结果变量为nil)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串值创建URL变量.我不明白为什么最终的URL为零

I'm trying to create an URL variable from a string value. I don't understand why the resulting URL is nil

我已经建立了一个新的Xcode macOS项目,在View上放置了一个简单的按钮,为该按钮创建了一个动作并实现了以下代码.生成的网址为nil.

I have set up a new Xcode macOS project, placed a simple button on the View, created an action for that button and implemented the following code. The resulting url is nil.

我在Swift游乐场尝试了同样的方法,并且效果很好...

I tried the same in Swift playground and there it worked...

    @IBAction func buttonClicked(_ sender: Any) {
        let urlAsString = "http://www.google.de/"
        let url = URL(string: urlAsString)

        if url != nil {
            // Do work...
        }
    }

urlAsString是" http://www.google.de/",但 网址为零

urlAsString is "http://www.google.de/" but url is nil

调试器

推荐答案

您在调试器中发现了一个错误!重现它很容易:

You've found a bug in the debugger! It's easy to reproduce it:

我们已经在条件内 的断点处暂停了.因此,显然url不是 nil,否则我们根本不会在这里.

We have paused at a breakpoint inside the condition. So obviously url is not nil or we wouldn't be here at all.

证明这一点的另一种方法是在控制台中单击po url(请参见此屏幕快照的右下角):

Another way to prove this is to po url in the console (see right-bottom of this screen shot):

尽管如此,url在工具提示和变量列表中均显示为nil.因此,调试器只是在骗你:url不是nil.别担心,要开心.您的代码运行正常.

Nevertheless, url shows as nil both in the tooltip and in the variables list. So the debugger is just lying to you: url is not nil. Don't worry, be happy. Your code is working fine.

编辑:该错误与Swift Foundation覆盖层有关.如果将url的声明更改为此:

EDIT The bug has something to do with the Swift Foundation overlay. If you change the declaration of url to this:

let url = NSURL(string: urlAsString)

...然后一切正常.

...then everything works as expected.

另请参见 https://stackoverflow.com/a/58156592/341994

这篇关于将String转换为URL(为什么结果变量为nil)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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