2017-07-10 27 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它在'基金會'之下,所以你必須擁有 –

相關問題