2016-09-29 46 views
1

我在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'. 

無法解決此錯誤。

很少解釋任何幫助,將理解

+0

你需要提供更多的細節。顯示如何聲明所有相關的變量和函數。 – rmaddy

+0

只需使用[String Interpolation](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html)。 –

回答

2

不同於夫特2,NSStringString不會自動相互之間進行轉換。

嘗試是這樣的:

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

您可以進一步清理它通過使用一致的類型 - 無論是StringNSString整個(例如改變函數返回等)。

+0

遵循你所說的和做了這個。但也添加了價值標籤。它讓我解決了。 newText =(「$」+ self.dollarStringFromInt(value:numOfPennies)+「。」+ self.centsStringFromInt(value:numOfPennies))as NSString – AK1

相關問題