Swift3 iOS - 如何在URL数组中搜索URL [URL?]

时间:2017-07-03 21:19:05

标签: ios arrays url search swift3

我有一系列网址。我想在该数组中搜索一个特定的元素,如果它在那里删除它。

let urls: [URL?] = [url_0, url_A, url_Purple, etc..]

//first search for url_A
if urls.contains(where: url_A){
     //second remove it from the array
     urls = urls.filter{$0 != url_A}
}

我尝试了trydo-try-catch,但他们没有成功。我知道我做错了,这就是我问这个问题的原因。

我收到错误:

  

无法将“网址”类型的值转换为预期的辩论类型'(URL)'   投掷 - >布尔

如何在网址数组中搜索网址?

1 个答案:

答案 0 :(得分:1)

根据您的问题,您可以这样做:

 let urls: [URL?] = [url_0, url_A, url_Purple, etc..]
 //second remove it from the array
 urls = urls.filter {$0 != url_A}

这将搜索url_A,如果找到它将删除它并返回新数组。如果我是对的,那就是你要找的。

根据你得到的错误答案:

let urls: [URL?] = [url_0, url_A, url_Purple, etc..]

//first search for url_A
if urls.contains(where: {$0 == url_A} ) == true {
     //second remove it from the array
     urls = urls.filter{$0 != url_A}
}

请注意,它期望在包含块中将闭包作为参数。您正在传递URL?类型。