Обновление количества ключей объекта путем добавления строки - PullRequest
1 голос
/ 01 апреля 2019

WatchKit имеет метод презентатора, который представляет QuickReplyButton с предопределенными текстовыми ответами, и эти ответы могут быть отправлены в элемент пользовательского интерфейса, такой как метка в ячейке / строке.

Я вставил строку в последнюю позицию, однако каждый последующий вызов вставляет новый ответ выше предыдущий ответ не ниже.

Я попытался добавить выбор текста в конец массива сообщений модели чата, используя self.chats.append(text as AnyObject), но выбор - строка, и я не могу добавить строку в массив модели чата. Value of type 'String' does not conform to 'AnyObject'. Если я полностью опущу self.chats.append(text as AnyObject), это будет работать так, как показано.

ChatDetailController

// ...
// start of @IBAction
// ...

    self.chats.append(text as AnyObject) // how do I write this?
    let newIndex = self.chats.count - 1
    //...

    })

Модель

public struct ChatModel: Codable {
    public var message: String
    // more properties

    enum CodingKeys: String, CodingKey {
        case message = "messageText"
        // more properties
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.message = try container.decode(String.self, forKey: .message)
        // more properties
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(self.message, forKey: .message)
        // more properties
    }

}

1020 * JSON *

[
  {
    "fromId": "wx1234skjksmsjdfwe234",
    "toId": "wx43922sdkfjsfmmxdfmx",
    "messageText": "Have you hopped on the bus Gus?",
    "imageUrl": "https://i.imgur.com/PJcyle7.jpg",
    "read": "true"
  },

// more objects.

]

1 Ответ

2 голосов
/ 02 апреля 2019

Я обновил ваш ChatModel. Используйте эту модель структуры. Вы можете инициировать из JSON декодера или из ваших значений времени выполнения.

public struct ChatModel: Codable {
public var message: String
public var fromId: String
public var toId: String
public var imageUrl: URL?

enum CodingKeys: String, CodingKey {
    case message = "messageText"
    case fromId = "fromId"
    case toId = "toId"
    case imageUrl = "imageUrl"
    //case read = "read"
}

init (message:String , fromId:String, toID : String, imgUrl : URL?) {
    self.message = message
    self.fromId = fromId
    self.toId = toID
    self.imageUrl = imgUrl
}

public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.message = try container.decode(String.self, forKey: .message)
    self.fromId = try container.decode(String.self, forKey: .fromId)
    self.toId = try container.decode(String.self, forKey: .toId)
    self.imageUrl = try container.decode(URL.self, forKey: .imageUrl)
    //self.read = try container.decode(Bool.self, forKey: .read)
}

public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(self.message, forKey: .message)
    try container.encode(self.fromId, forKey: .fromId)
    try container.encode(self.toId, forKey: .toId)
    try container.encode(self.imageUrl, forKey: .imageUrl)
    //try container.encode(self.read, forKey: .read)
}

}

И вот как вы можете создать объект chatModel для вставки в массив чатов

Примечание: используйте тот же fromID и ToID, которые вы получили от json

    let newChat = ChatModel(message: "test", fromId: "fromID", toID: "tOID", imgUrl: nil)
    self.chats.append(newChat)

Теперь вставьте строку в таблицу в конце

...