Get Specific URLQueryItem from URLComponents

Consider the following URL:

We are interested in the query parameter value of utm_term. We can parse the URL using the following code:

func queryParam(urlString: String?, param: String) -> String? {
guard let urlString = urlString else { return nil }
guard let urlComponents = URLComponents(string: urlString) else { return nil }
guard let queryItems = urlComponents.queryItems else { return nil }
return queryItems.filter { queryItem in
return == param

And call the function using: