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

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

问题描述

我正在尝试从字符串值创建 URL 变量.我不明白为什么结果 URL 为 nil

我已经建立了一个新的 Xcode macOS 项目,在视图上放置了一个简单的按钮,为该按钮创建了一个操作并实现了以下代码.结果网址为零.

我在 Swift 的操场上尝试了同样的方法,结果奏效了......

 @IBAction func buttonClicked(_ sender: Any) {让 urlAsString = "http://www.google.de/"让 url = URL(string: urlAsString)如果网址 != nil {//做工作...}}

urlAsString 是

我们在条件内部的断点处暂停.所以很明显 urlnot nil 否则我们根本就不会在这里.

证明这一点的另一种方法是在控制台中po url(请参阅此屏幕截图的右下角):

尽管如此,url 在工具提示和变量列表中都显示为 nil.所以调试器只是在骗你:url 不是 nil.别担心,开心就好.您的代码运行良好.

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

let url = NSURL(string: urlAsString)

...然后一切都按预期进行.

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

I'm trying to create an URL variable from a string value. I don't understand why the resulting URL is 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.

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 is "http://www.google.de/" but url is nil

debugger

解决方案

You've found a bug in the debugger!

[This bug is slated to be fixed in Xcode 12.5.]

It's easy to reproduce it:

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

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

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.

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.

And see also https://stackoverflow.com/a/58156592/341994

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

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