更改嵌套字典键的值

时间:2017-12-09 17:47:34

标签: swift dictionary nested

我有以下var需要更改/更新,例如&#39; &#39; <&em> 39; ,其中包含用户输入的值。

 var calendarEvent = [
        "subject": "Let's go for lunch",
        "body": [

                "contentType": "HTML",
                "content": "Does late morning work for you?",

        ],
        "start": [

                "dateTime":"2017-12-10T12:55:00",
                "timeZone": "W. Europe Standard Time"

        ],
        "end": [

                "dateTime": "2017-12-10T14:00:00",
                "timeZone": "W. Europe Standard Time"

        ],
        "location": [

                "displayName": "Antwerpen"

        ],
        "attendees": [],
] as [String: AnyObject]

让我们说我们不关心用户输入 - 因为它只是一个字符串 - 而只是想用这个词替换值&#39; yea boi&#39;

我该怎么做?

1 个答案:

答案 0 :(得分:1)

最不容易出错,最容易和最便携的方法是定义结构并使用Codable协议以及JsonEncoderJsonDecoder来为您的JSON字符串读取和写入端点。然后,如果您需要更改某个key,您可以将其视为任何其他结构并直接更改。

import Foundation

// structures for encoding/decoding

struct Body: Codable {
  let contentType: String
  let content: String
}

struct Time: Codable {
  let dateTime: String
  let timeZone: String
}

struct Location: Codable {
  let displayName: String
}

struct CalendarEvent: Codable {
  var subject: String // mutable
  let body: Body
  let start: Time
  let end: Time
  let location: Location
  let attendees: [String]
}

// set up structure

var event = CalendarEvent(subject: "Let's go for lunch",
                body: Body(contentType: "HTML",
                            content: "Does late morning work for you?"),
                start: Time(dateTime:"2017-12-10T12:55:00",
                             timeZone: "W. Europe Standard Time"),
                end: Time(dateTime:"2017-12-10T14:00:00",
                           timeZone: "W. Europe Standard Time"),
                location: Location(displayName: "Antwerpen"),
                attendees: [])

// change the subject
event.subject = "yea boi"

// create encoder

let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = [.prettyPrinted, .sortedKeys]

// encode, convert to a String, and print it

if let jsonData = try? jsonEncoder.encode(event),
  let jsonString = String(data: jsonData, encoding: .utf8) {
  print(jsonString)
}

// output

/* {
     "attendees" : [],
     "body" : {
       "content" : "Does late morning work for you?",
       "contentType" : "HTML"
     },
     "end" : {
       "dateTime" : "2017-12-10T14:00:00",
       "timeZone" : "W. Europe Standard Time"
     },
     "location" : {
       "displayName" : "Antwerpen"
     },
     "start" : {
       "dateTime" : "2017-12-10T12:55:00",
       "timeZone" : "W. Europe Standard Time"
     },
     "subject" : "yea boi"
   }
*/

注意变异的主题,从“让我们去吃午餐”改为“是的boi”。

相关问题