二进制运算符'+'不能应用于两个String操作数

时间:2015-07-21 10:39:06

标签: ios xcode swift

您好我对某些代码有疑问。

好的,问题是我有一些代码可以在一个函数中运行,但在另一个函数中给我一个错误。第一个代码块是它工作的功能。 顺便说一下,它只有一行:

@IBAction func searchPhotosByPhraseButtonTouchUp(sender: UIButton) {

    if (!searchText.text.isEmpty) {

        // 2: Replace spaces with +
        var escapedSearchText:String = searchText.text.stringByReplacingOccurrencesOfString(" ", withString: "+")

        // 3: API Method arguments
        let methodArguments = [
            "method": METHOD_NAME,
            "api_key": API_KEY,
            "text": escapedSearchText,
            "format": FORMAT,
            "nojsoncallback": NO_JSON_CALLBACK,
            "extras": EXTRAS,
            "safe_search": SAFE_SEARCH
        ]

        // This line is the problem, if i make it in this function there is no problems
        let urlString = BASE_URL + encodeParameters(params: methodArguments)

        // 4: Call the Flickr API with these arguments
        getImageFromFlickrBySearch(methodArguments)
    }
    else {
        self.imageInfoLbl.text = "You did not write anything in the textfield"
    }
}

正如您所看到的,在上面的代码块中一切都很好,但如果我这样做:

func getImageFromFlickrBySearch(methodArguments: [String: AnyObject]) {

    // 5: Initialize session and url
    ...
    // Here it gives me the error: 
    // Binary operator '+' cannot be applied to two String operands
    let urlString = self.BASE_URL + encodeParameters(params: methodArguments)
    ...
}

我收到错误。 为清楚起见,我已从第二个代码块功能中删除了其余代码。

我应该说BASE_URL是常数。

功能的唯一区别是,一个是@IBAction ??

1 个答案:

答案 0 :(得分:0)

我对Swift并不太熟悉,但可能导致错误的是methodArguments: [String: AnyObject]。在有效的函数中,Swift知道字典中的所有对象都是String对象,但在第二个函数中,它们的类型是AnyObject

如果所有键/值对都是字符串,请将参数更改为methodArguments: [String: String],看看是否有效。

相关问题