2015-06-18 67 views
6

一直試圖讓這對雨燕2.0工作,錯誤說:使用NSSerialization.datawithJSON斯威夫特2

類型NSJSONWritingOptions不能遵守協議NilLiteralConvertible

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 "" 
} 

回答

13
let options = prettyPrinted ? 
     NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0) 

是swift 2.0的正確語法

5

您還可以傳遞一個空數組沒有選項:

let options:NSJSONWritingOptions = prettyPrinted ? .PrettyPrinted : []