gpt4 book ai didi

具有值类型的 JSONSerialization

转载 作者:行者123 更新时间:2023-11-30 13:11:32 25 4
gpt4 key购买 nike

我想使用 Foundation 的 JSONSerialization.data(withJSONObject obj: AnyObject, options opt:writingOptions = []) throws -> Data 。但是,我不知道如何将我的值类型转换为适合该方法使用的引用类型。

例如,尝试序列化一个简单的字符串数组会失败,因为该方法需要引用类型,而不是值类型:

root@1c6c66df21cf:/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]() )

转换不起作用:

root@1c6c66df21cf:/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 中的示例对于该版本的核心基础:

root@1c6c66df21cf:/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

供引用的系统信息:

root@1c6c66df21cf:/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
root@1c6c66df21cf:/tmp# swift --version
Swift version 3.0 (swift-3.0-PREVIEW-3)
Target: x86_64-unknown-linux-gnu

最佳答案

使用.bridge()是正确的方法。该错误特定于 REPL。编译整个文件时不会发生这种情况:

root@1c6c66df21cf:/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)!)
root@1c6c66df21cf:/tmp# swift test.swift
["string"]
root@1c6c66df21cf:/tmp# swiftc -o test test.swift
root@1c6c66df21cf:/tmp# ./test
["string"]

关于具有值类型的 JSONSerialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38670942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com