簡體   English   中英

在 Swift 中將 CGPoint 數組轉換為字符串

[英]Convert CGPoint array to String in Swift

我有一系列的點,如:

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

我從這個數組中創建了一個字典作為

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

我創建了一個 jsondata 來創建一個 json 字符串,如下所示

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

但我收到錯誤如下:

由於未捕獲的異常“NSInvalidArgumentException”而終止應用程序,原因:“JSON 寫入中的無效類型 (NSConcreteValue)”。

元組不可編碼,但 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