获取错误 否 '+'候选项生成预期的上下文结果类型'NSString'



我在swift 3和Xcode 8中编写代码。

代码如下:

import Foundation
import UIKit
class CashTextFieldDelegate : NSObject, UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let oldText = textField.text! as NSString
    var newText = oldText.replacingCharacters(in: range, with: string) as NSString
    var newTextString = String(newText)
    let digits = NSCharacterSet.decimalDigits
    var digitText = ""
    for c in newTextString.unicodeScalars {
        if digits.contains(c) {
            digitText.append(String(c))
        }
    }
    // Format the new string
    if let numOfPennies = Int(digitText) {
        newText = "$" + self.dollarStringFromInt(numOfPennies)+ "." + self.centsStringFromInt(numOfPennies)
    } else {
        newText = "$0.00"
    }
    textField.text = newText as String
    return false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField.text!.isEmpty {
        textField.text = "$0.00"
    }
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true;
}
func dollarStringFromInt(value: Int) -> String {
    return String(value / 100)
}
func centsStringFromInt(value: Int) -> String {
    let cents = value % 100
    var centsString = String(cents)
    if cents < 10 {
        centsString = "0" + centsString
    }
    return centsString
}
}

表示上面这行代码:

newText = "$" + self.dollarStringFromInt(numOfPennies) + "." + self.centsStringFromInt(numOfPennies)

我得到这样的错误:

No '+' candidates produce the expected contextual result type 'NSString'.

无法解决此错误。

如果有任何帮助,只要稍加解释,我将不胜感激

与Swift 2不同,NSStringString之间不会自动转换。

试试这样写:

newText = ("$" + self.dollarStringFromInt(numOfPennies) + "." + self.centsStringFromInt(numOfPennies)) as NSString

你可以通过使用一致的类型——StringNSString来进一步清理它(例如改变函数返回值等)。

最新更新