2016-07-30 25 views
0

我想使用基金會的JSONSerialization.data(withJSONObject obj: AnyObject, options opt: WritingOptions = []) throws -> Data。但是,我無法弄清楚如何將我的值類型轉換爲適合該方法使用的引用類型。JSON與值類型的串行化

例如,試圖連載簡單字符串數組失敗,因爲該方法需要一個引用類型,而不是一個值類型:

[email protected]:/tmp# swift 
Welcome to Swift version 3.0 (swift-3.0-PREVIEW-3). Type :help for assistance. 
    1> import Foundation 
    2> JSONSerialization.data(withJSONObject: [String]()) 
error: repl.swift:2:48: error: argument type '[String]' does not conform to expected type 'AnyObject' 
JSONSerialization.data(withJSONObject: [String]()) 

鑄造不起作用:

[email protected]:/tmp# swift 
Welcome to Swift version 3.0 (swift-3.0-PREVIEW-3). Type :help for assistance. 
    1> import Foundation 
    2> let value = [String]() 
value: [String] = 0 values 
    3> let reference = value as! NSArray 
reference: Foundation.NSArray = <extracting data from value failed> 

Execution interrupted. Enter code to recover and continue. 
Enter LLDB commands to investigate (type :help for assistance.) 

我也嘗試以該版本的核心基金會unit tests爲例:

[email protected]:/tmp# swift 
Welcome to Swift version 3.0 (swift-3.0-PREVIEW-3). Type :help for assistance. 
    1> import Foundation 
    2> let value = [String]() 
value: [String] = 0 values 
    3> let reference = value.bridge() 
reference: Foundation.NSArray = <extracting data from value failed> 

error: Couldn't lookup symbols: 
    (extension in Foundation):Swift.Array.bridge() -> Foundation.NSArray 

參考系統信息:

[email protected]:/tmp# uname -a 
Linux 1c6c66df21cf 4.4.12-boot2docker #1 SMP Wed Jun 1 22:45:59 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux 
[email protected]:/tmp# swift --version 
Swift version 3.0 (swift-3.0-PREVIEW-3) 
Target: x86_64-unknown-linux-gnu 

回答

0

使用.bridge()是正確的做法。該錯誤是特定於REPL的。編譯整個文件時不會發生這種情況:

[email protected]:/tmp# cat test.swift 
import Foundation 

let value = ["string"] 
let reference = value.bridge() 
let jsonData = try! JSONSerialization.data(withJSONObject: reference) 
print(String(data: jsonData, encoding: .utf8)!) 
[email protected]:/tmp# swift test.swift 
["string"] 
[email protected]:/tmp# swiftc -o test test.swift 
[email protected]:/tmp# ./test 
["string"] 
相關問題