home ~ projects ~ socials

Convert A String To A Number In Swift

Notes

  • These are snippets I grabbed from working code but they haven't been tested individually. They are just scratch notes for right now
  • I'm not yet sure how to add a do/try/catch to make sure it worked
let numberAsString = "5"
let numberAsNumber = Int32(truncating: NumberFormatter().number(from: numberAsString)!)

I think this might work too:

let numberAsString = "1.2"
let numberAsNumber = (Double(parts[1]) ?? 0.0))
-- end of line --