0

I read dozens of posts but it looks like many things have changed with strings between Swift 2, Swift 3 and Swift 4, and I could not find a useful example of something working.

I'm currently using Swift 3.1.

I get some strings from a server and I need to left trim the zeroes and convert them to integers.

The strings come in this format:
"00000123", "00123456", "012" and "000" too.

So, the string 00000123 should become 123, 012 should be converted to the integer 12 and 000 (and 0000, 00000, 000000, etc.) should be converted to 0.

Can you help me?

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223

1 Answers1

0

Int converting in Swift does this by default.

Int("00000123") //123
Int("012") //12
Int("000") //0
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • You need to be careful here, it's not that simple because depending on the string it can overflow – TNguyen Nov 30 '17 at 19:38
  • Of course, integers can overflow, but it was OP's demand to convert strings to integers. – Tamás Sengel Nov 30 '17 at 19:50
  • @TNguyen: please, can you elaborate a little? –  Dec 01 '17 at 07:25
  • @the4kman: do I need to force unwrap it? This returns an optional Int, right? –  Dec 01 '17 at 07:30
  • 1
    @3000. It does return an optional, but **don't force unwrap values that come from an external source.** (Some say don't force unwrap at all, but in some cases, it's acceptable. This, however, is not one of those cases.) – Tamás Sengel Dec 01 '17 at 11:50
  • @the4kman: what do you generally do when the value is expected as non-optional? Eg. in this case, the value should be of type Int because a function needs it to be an Int –  Dec 01 '17 at 12:32
  • Check if the value is non-nil with `if let` or `guard let` or provide a default value by using two question marks (`??`). Check out [this question](https://stackoverflow.com/q/24034483/3151675) for details. – Tamás Sengel Dec 01 '17 at 12:34
  • @the4kman: of course, this is what I generally do. I thought there was something you do I didn't know of :-) The force-unwrap in my particular case is ok because there are tons of checks before the value even "arrives" where it is needed. Moreover, I control the server code too, so it's literally impossible something wrong occurs :-) –  Dec 01 '17 at 13:03