使用 swift 中函数的字符串无法成功创建 URL 的原因是什么?

What's the reason that I can not successfully create an URL by using a string from a function in swift?

我是 IOS 开发的新手,最近参加了一门在线课程。对于一个 fetchWeather(cityName: String) 函数,我试图通过一个字符串创建一个 URL,该字符串具有天气预报网站的名称、我的 API 键和城市名称。但是,我发现如果我使用函数中的 cityName,URL 会失败。有线的事情是如果我不使用参数值,而是在函数中创建一个新的局部变量 city_namecityName 具有相同的值,这是参数值, [=27= 】 成功。这是我的两个测试用例:

func fetchWeather(cityName: String) {
        // The first case that use the argument of the function
        print("First test case: ")
        print(cityName)
        let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid=2b5e3c1ae10223238e8bbf73b814e563&units=metric&q="
        let first_urlString = weatherURL+cityName
        guard let first_url = URL(string:first_urlString)  else{
            print("First_URL fails")
        
        // The second case that directly combine two strings
            print("\nSecond test case: ")
            let city_name = "London"
            let second_url_String = weatherURL + city_name
            guard let second_url = URL(string:second_url_String)  else{
                print("Second_URL fails")
                return
            }
            print("Second_URL succeed")
            
            print("\n"+first_urlString)
            print(second_url_String)
            print("The first string is equals to the second string: " + String(first_urlString==second_url_String))
            
            return
        }
        print("First_URL succeed")
        
        
    }

这是输出:

First test case: 
London 
First_URL fails

Second test case: 
Second_URL succeed

https://api.openweathermap.org/data/2.5/weather?appid=2b5e3c1ae10223238e8bbf73b814e563&units=metric&q=London 
https://api.openweathermap.org/data/2.5/weather?appid=2b5e3c1ae10223238e8bbf73b814e563&units=metric&q=London
The first string is equals to the second string: false

那两个url_strings长得一模一样,为什么不一样呢?我相信这两个 url_strings 之间的区别是我的第一个 URL 失败而第二个成功的问题。

干得好,将您的确切输出剪切并粘贴到您的问题中。我就是这样诊断出来的。

您传递给 fetchWeathercityName 结尾有一个 U+0020 SPACE

00000000  4c 6f 6e 64 6f 6e 20                              |London |
00000007

URL 解析器不喜欢这样。试试这个:

let first_urlString = weatherURL + cityName.trimmingCharacters(in: .whitespacesAndNewlines)