2017-07-10 29 views
0

例如我只想这个样本数组转换成JSON对象使用未解决的标识符“JSONEncoder” swift4

var test = [String : Any]() 
test["title"] = "title" 
test["description"] = "description" 
test["date"] = Date.init() 

,我得到这个错误:

use of unresolved identifier 'JSONEncoder' 
print(JSONEncoder (test)) 
+1

您是否进口基金会?你确定你正在运行Swift 4吗?什么是“swift -version”输出? – Hamish

回答

1

您没有使用编码器正确。试试这个

let encoder = JSONEncoder() 
let json = try? encoder.encode(test) 

引用的应用程序的文件here,唯一的init()方法是这样的,所以你不应该建立在编码器本身,让你的JSON结果。

init()

Creates a new, reusable JSON encoder with the default formatting settings and encoding strategies.

+1

请注意,尽管编译(使用Foundation导入),但它会在运行时崩溃,因为'[String:Any]'不是'Encodable'。 – Hamish

+0

我想我不会输入我必须输入的东西,对于“JSONEncoder”,我应该输入一些特别的东西吗? – Amir

+1

@Amir它在'基金会'之下,所以你必须拥有 –

相关问题