Use NSSerialization.datawithJSON in Swift 2

Trying to get this to work in Swift 2.0, the error says:

NSJSONWritingOptions type cannot conform to NilLiteralConvertible protocol

at var options = prettyPrinted... :

 func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String { var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil if NSJSONSerialization.isValidJSONObject(value) { do{ let data = try NSJSONSerialization.dataWithJSONObject(value, options: options) if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return string as String } } catch { } } return "" } 
+6
source share
2 answers
 let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0) 

- correct syntax for swift 2.0

+13
source

You can also pass an empty array without parameters:

 let options:NSJSONWritingOptions = prettyPrinted ? .PrettyPrinted : [] 
+5
source

Source: https://habr.com/ru/post/989356/


All Articles