0

I'm writing a function that given an array of objects that contain a property called url, remove all objects with bad urls.

Here's what I have:

func cleanArray(data:[String: Any])->Void {
   let uris = data.filter{($0["url"] as! String).range(of: #"^(https?|file|ftp)"#, options: .regularExpression) != nil };
}

But xcode is showing an error in $0:

Value of tuple type '(key: String, value: Any)' has no member 'subscript'

Cornwell
  • 3,304
  • 7
  • 51
  • 84
  • 1
    To check that a string is a valid URL, have a look here https://stackoverflow.com/questions/28079123/how-to-check-validity-of-url-in-swift/36012850 – ielyamani Sep 10 '19 at 11:44
  • You shouldn't do URL operations like this on a raw `String`. You should extract the data from your dictionary into structs, and perform this validation in the initializer of your struct. Your code doesn't even need a regex. It would be much simpler if just used the URL API, which would allow you to write: `["http", "https", "file", "ftp"].contains(url.scheme)` – Alexander Sep 10 '19 at 12:58

1 Answers1

2

[String: Any] is a dictionary , You need [[String: Any]]

func cleanArray(data:[[String: Any]]) -> Void { 
    let uris = data.filter{ ($0["url"] as! String).range(of: #"^(https?|file|ftp)"#, options: .regularExpression) != nil };
}

This could be more object oriented if you make it an array of a model

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87