-3

I get json from server and I need to convert id field to string in swift code.

The problem is json sometimes returns "12345", sometimes returns 12345 (with or without quotes).

Is it possible to resolve this issue without of checking the value type and checking if the conversion result is nil?

UPDATED

Example of code I use with checking conversion result:

let result = (some_index as? String) ?? String(some_index as! Int)

The problem is in objective-C you have [NSString stringWithFormat:@"%@", some_object]. But in swift you have optionals and it tries to insert word "optional" into result.

UPDATED

STOP spam with random answers about optionals. The question is concrete - "how to simply unwrap json value which may look like String, Int or doesn't exist at all?"

swift How to remove optional String Character

In this question they ask how to convert Int? -> Int, String? -> String and similar. In my case I don't know if I have Int? or String? as the initial type.

Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49
  • Update your question with your current relevant code and clearly show what you need help with. – rmaddy Sep 06 '17 at 15:12
  • Why is that a problem to check the value type and check if the conversion has failed? If value is inconsistently a String or an Int, you have to check yourself, no other magical way. – Eric Aya Sep 06 '17 at 15:12
  • Do you actually want to store a String or `Int` value? Moreover, as already requested by others, please provide more context. – Dávid Pásztor Sep 06 '17 at 15:14
  • Why does the server return quotation marks sometimes and the other times not. That's a very odd behaviour – TNguyen Sep 06 '17 at 15:15
  • @TPN1994, the problem appeared when project was rewritten into swift with its optionals – Vyachaslav Gerchicov Sep 06 '17 at 15:22
  • @VyachaslavGerchicov I would opt to use guards instead. If the conversion to int fails it will crash. – TNguyen Sep 06 '17 at 15:24
  • Possible duplicate of [swift How to remove optional String Character](https://stackoverflow.com/questions/26347777/swift-how-to-remove-optional-string-character) – Dávid Pásztor Sep 06 '17 at 15:25

1 Answers1

0

Both Stringand Int conform to CustomStringConvertible, so you could optional downcast the value to CustomStringConvertible and use String Interpolation

let dict : [String:Any] = ["Foo" : 12345]

if let value = dict["Foo"] as? CustomStringConvertible {
    let result = "\(value)"
}

And blame the owner of the web service for sending inconsistent data ;-)

vadian
  • 274,689
  • 30
  • 353
  • 361