AK1 AK1 - 2 months ago 38
iOS Question

Getting a error No '+' candidates produce the expected contextual result type 'NSString'

I am writing the code in swift 3 and Xcode 8.

Here is the code:

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
}

}


for this line of code from above :

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


I get a error like this:

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


Unable to resolve this error.

Any help with little explanation would be appreciated

Answer

Unlike Swift 2, NSString and String aren't automatically converted between each other.

Try something like this:

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

You can further clean this up by using a consistent type-- either String or NSString throughout (e.g. changing function returns, etc).

Comments