简体   繁体   English

字符串数组未转换为 swift 中的 url

[英]string array not converting to url in swift

I have a array which is declared as below var photoarray = String The values which are in the photoarray is as follows:我有一个数组,声明如下 var photoarray = String photoarray 中的值如下:

["https://res.cloudinary.com/dtwvevtm7/image/upload/v1606166095/wdfub3plecnhmixbwtgw.jpg", " https://res.cloudinary.com/dtwvevtm7/image/upload/v1606166095/dbzvkv8qhtwhgbocuzwb.jpg"]

Since it is an array, it is passed into for loop and this string is converted to URL.由于它是一个数组,所以它被传递到for循环中,这个字符串被转换为URL。 When it is converted to url, it is showing当它转换为 url 时,它显示

Fatal error: Unexpectedly found nil while unwrapping an Optional value.致命错误:在展开 Optional 值时意外发现 nil。

The code which is used to retrieve the url is as follows:用于检索 url 的代码如下:

for i in 0..<self.photoarray.count
{
    let url = URL(string: self.photoarray[i])
    print("url is", url)
    self.images.append(LightboxImage(imageURL: url!))
}

It is showing the first value of the array when url is printed, but the next value is showing nil .打印 url 时显示数组的第一个值,但下一个值显示nil What is the issue?问题是什么?

There is a blank space in the first character of your second url string in the photoarray . photoarray 中第二个photoarray字符串的第一个字符中有一个空格。 Remove it.去掉它。 URL initializer returns nil if the string doesn't represent a valid URL.如果字符串不代表有效的 URL,则URL初始化程序将返回 nil。 Also its better not using force unwrapping here.此外,最好不要在这里使用强制展开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM