简体   繁体   English

在 Swift 中将 CGPoint 数组转换为字符串

[英]Convert CGPoint array to String in Swift

I have array of points like:我有一系列的点,如:

[(32.33332824707031, 237.0), (105.33332824707031, 355.3333282470703), (124.0, 355.3333282470703), (165.3333282470703, 240.0), (116.33332824707031, 199.66665649414062)]

I created a dictionary out of this array as我从这个数组中创建了一个字典作为

let dic : Dictionary<String, [CGPoint]> = [ "ARRAY" : points]

I create a jsondata to create a json string as below我创建了一个 jsondata 来创建一个 json 字符串,如下所示

let jsonData = try? JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)

But i am getting error as:但我收到错误如下:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteValue)'.由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“JSON 写入中的无效类型 (NSConcreteValue)”。

Tuples aren't codable but CGPoint is so either keep your original CGPoint array if you have one or map the array from tuple to CGPoint元组不可编码,但 CGPoint 可以保留原始 CGPoint 数组(如果有)或将数组从元组映射到 CGPoint

let points = array.map {CGPoint(x: $0.0, y: $0.1)}

let dic : Dictionary<String, [CGPoint]> = [ "ARRAY" : points]
do {
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted

    let data = try encoder.encode(dic)
    print(String(data: data, encoding: .utf8)!)
} catch {
    print(error)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM