Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 替换Swift 2中的字符串_Ios_Swift_Swift2 - Fatal编程技术网

Ios 替换Swift 2中的字符串

Ios 替换Swift 2中的字符串,ios,swift,swift2,Ios,Swift,Swift2,因此,我正在尝试为iOS 9构建应用程序,但遇到了一个问题。以前,我有一个按钮,可以从标签中提取字符串,并将其添加到字符串中,该字符串可以让人进入lmgtfy并自动搜索字符串的内容,但现在我在map()中遇到了一个错误。以下是在iOS 8中工作的代码: @IBAction func googleButton() { let replaced = String(map(originalString.generate()) { $0 == " " ? "+" : $0

因此,我正在尝试为iOS 9构建应用程序,但遇到了一个问题。以前,我有一个按钮,可以从标签中提取字符串,并将其添加到字符串中,该字符串可以让人进入lmgtfy并自动搜索字符串的内容,但现在我在map()中遇到了一个错误。以下是在iOS 8中工作的代码:

        @IBAction func googleButton() {
        let replaced = String(map(originalString.generate()) { $0 == " " ? "+" : $0 })
        if let url = NSURL(string: "http://google.com/?q=\(replaced)") {
            UIApplication.sharedApplication().openURL(url)
        }

            print(replaced)
        }

所以现在我得到的错误是,“'map'不可用:调用序列上的'map()'方法。”有什么想法吗?另外,我不确定该链接是否有效,因为它应该是lmgtfy,但除非我将URL更改为google,否则我无法提交此问题。

从Swift 2开始,
String
不再符合,因此您不能在其上调用
generate
。相反,您需要使用
characters
属性来获取符合
SequenceType

同样对于Swift 2:
map
SequenceType
扩展中的一种方法。因此,您可以像调用方法一样调用它,而不是调用自由函数:

let str = "ab cd ef gh"
let replaced = String(str.characters.map { $0 == " " ? "+" : $0 }) 
// "ab+cd+ef+gh"
你也可以这样做:

let replaced = str.stringByReplacingOccurrencesOfString(" ", withString: "+")
// "ab+cd+ef+gh"

originalString.generate()。看来这解决了我的问题!非常感谢。