swift2 - 在 Swift 2 中使用 NSSerialization.datawithJSON

标签 swift2 nsjsonserialization

一直试图让它在 Swift 2.0 中工作,错误提示:

Type NSJSONWritingOptions cannot conform to protocol 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 ""
}

最佳答案

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

是 swift 2.0 的正确语法

关于swift2 - 在 Swift 2 中使用 NSSerialization.datawithJSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30920766/

相关文章:

ios - Swift 2 reloadData 向 UICollectionView 添加了更多单元格

ios - 使用 NSJSONSerialization 解析具有多个数组的 JSON 字典不会导致 NSDictionary 或 NSArray

ios - 解析JSON数据的JSON结构

ios - 警告 : Attempt to present View Controller on * which is already presenting <UISearchController: 0x142a1f7c0>

ios - 如何在 objective-c 中创建 json

php - 在展开可选值 JSON 序列化时发现 nil

ios - FHSTwitterEngine- 'NSInvalidArgumentException' ,'data parameter is nil'

ios - Swift 3 中的 AVAudiosessionInterruptionNotification

swift - 修复 NSURLConnection 弃用从 Swift 1.2 到 2.0

swift - 获取声明为协议(protocol)的属性时调用 didSet