2016-07-30 2 views
0

Foundation의 JSONSerialization.data(withJSONObject obj: AnyObject, options opt: WritingOptions = []) throws -> Data을 사용하고 싶습니다. 그러나 필자는 값 유형을 해당 메소드와 함께 사용할 수있는 적합한 참조 유형으로 변환하는 방법을 알 수 없습니다.값 형식을 사용하는 JSONSerialization

[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.) 

방법은 참조 형식이 아닌 값 형식이 필요하기 때문에 단순한 문자열 배열에는 직렬화하려고 예를 들어

가 실패 해당 버전의 코어 Foundation에 대한 의 예를 따르십시오.
[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 
01 참조 23,414,시스템 정보 :

[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"] 
관련 문제