You solved my two problems:
- I only need to handle
Numeric
types, so<T: Numeric>
is good enough - The
NSNumber
comes from theFormatter
ofTextField
, I got rid of theconvert
and just do cast directly, theas! T
should be safe sinceT: Numeric
?:
@objc func doneAction(_ button: UIBarButtonItem) {
field = (formatter.number(from: textField.text ?? "0") ?? NSNumber(value: 0)) as! T
textField.resignFirstResponder()
}
How does cast to any numeric work with NSNumber
? Can I write my own type that can do this?
let d = 1.23
let I = d as! Int // this will crash, so how does NSNumer do this?