简体   繁体   中英

NSNumber? to a value of type String? in CoreData

So I can't figure this out, am I supposed to change the '.text' to something else or do I have to go about converting the string into a double?

Here is the code

if item != nil {
    // the errors I keep getting for each one is
    unitCost.text = item?.unitCost //cannot assign to a value 'NSNumber?' to a value of type 'String?'
    total.text = item?.total  //cannot assign to a value 'NSNumber?' to a value of type 'String?'
    date.text = item?.date //cannot assign to a value 'NSDate?' to a value of type 'String?'
}

You are trying to assign an invalid type to the text property. The text property is of type String? as stated by the compiler error. You are trying to assign an NSNumber or NSDate . The expected type is a String or nil and so you must ensure that you provide only those two possibilities. As a result, you need to convert your numbers and dates into strings.

In Swift, there is no need to use format specifiers. Instead, best practice is to use string interpolation for simple types like numbers:

unitCost.text = "\(item?.unitCost!)"
total.text    = "\(item?.total!)"

For dates, you can use NSDateFormatter to produce a human-friendly date in a desired format:

let formatter       = NSDateFormatter()
formatter.dateStyle = .MediumStyle

date.text           = "\(formatter.stringFromDate(date))"

While we're at it, why not use optional binding instead of nil comparison:

if let item = item {
    // Set your properties here
}

尝试这个:

unitCost.text = String(format: "%d", item?.unitCost?.integerValue)

You can add an extension for Double/NSNumber/NSDate

extension Double {
    func toString() -> String {
        return NSNumberFormatter().stringFromNumber(self) ?? ""
    }
}

extension NSNumber {
    func toString() -> String {
        return NSNumberFormatter().stringFromNumber(self) ?? ""
    }
}

var doubleValue: Double?
doubleValue?.toString()

if doubleValue is not set it returns empty string. You can make toString() return String? too.. depends on what you need

also, item != nil check is not required in your code as it is optional.

@dbart“ \\(item?.unitCost)”将可选值显示为String,就像Optional(5)而不是5一样,我们需要解开该值

check this code:

if let requiredItem = item {
unitCost.text = requiredItem.unitCost ? "\(requiredItem.unitCost)" : ""
total.text = requiredItem.total ? "\(requiredItem.total)" : ""
date.text = requiredItem.date ? "\(requiredItem.date)" : ""
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM