With only <T: Numeric> type, how to create an NSNumber?

struct NumberField<T: Numeric & CustomStringConvertible>: View {
    @Binding var value: T
    let formatter: NumberFormatter

    var body: some View {
        // how can I create an NSNumber from `value`?
        // this doesn't work:
        let n1 = NSNumber(value: value)    // No exact matches in call to initializer 

        // This work, but seem not ideal
        let n2 = formatter.number(from: value.description) ?? NSNumber(value: 0)
    }
}

You can't; Numeric is a very general protocol, and lots of things that can conform to Numeric (like say Complex<Double> from Swift Numerics or a type that represents polynomials with integer coefficients) have no sensible representation as NSNumbers.

Given that you want to do this, it's safe to say that your constraint should be significantly more restrictive than Numeric; what are the actual requirements for the types you need to represent?

Edit: solution to this question.

All the numeric types NSNumber support except Bool and CChar, exactly these I copy from all the init(value:)'s:

Double
Float
Int32
Int
Int64
Int16
UInt8
UInt32
UInt
UInt64
UInt16

this is my original question about casting an NSNumber to a <T: that-NSNumber-Support-Except-Bool-And-CChar>

Terms of Service

Privacy Policy

Cookie Policy