在swift中将字符串转换为google可搜索字符串

在swift中将字符串转换为google可搜索字符串,swift,url,search,Swift,Url,Search,我想打开谷歌搜索任何给定字符串,这是我的代码,但它不会打开搜索给定字符串的例子 let s = "A long-running line of '80s ads urged potential pizza customers to “avoid” what?" let search = s.replacingOccurrences(of: " ", with: "+") if let url = URL(string: "https://www.google.com/search?q=\(

我想打开谷歌搜索任何给定字符串,这是我的代码,但它不会打开搜索给定字符串的例子

let s = "A long-running line of '80s ads urged potential pizza customers to “avoid” what?"
let search = s.replacingOccurrences(of: " ", with: "+")



if let url = URL(string: "https://www.google.com/search?q=\(search)"), NSWorkspace.shared.open(url) {
        print("default browser was successfully opened")

    }

字符串中还有其他字符需要正确转义,而不仅仅是空格

let s = "A long-running line of '80s ads urged potential pizza customers to “avoid” what?"
let search = s.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

if let search = search, let url = URL(string: "https://www.google.com/search?q=\(search)"), NSWorkspace.shared.open(url) {
    print("default browser was successfully opened")
} else {
    print("Can't create search URL with \(search)")
}