我在SWIFT 3編寫代碼和Xcode的8得到一個錯誤沒有「+」候選人產生預期的語境結果類型「的NSString」
下面是代碼:
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'.
無法解決此錯誤。
很少解釋任何幫助,將理解
你需要提供更多的細節。顯示如何聲明所有相關的變量和函數。 – rmaddy
只需使用[String Interpolation](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html)。 –