JSONModel无法与Swift数组一起使用 [英] JSONModel not working with Swift arrays

查看:180
本文介绍了JSONModel无法与Swift数组一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中使用JSONModel时遇到了一些麻烦.

I am having some trouble using JSONModel in Swift.

我正在尝试创建一个待办事项列表应用程序,该应用程序将保留一组项目,以便在该应用程序关闭时保留待办事项.这是我使用的代码:

I am trying to create a ToDo list app that would persist a collection of items so that the ToDo items are preserved when the app is closed. This is the code I use:

class ToDoItem: JSONModel {
    var name: String = ""
    var isCompleted: Bool = false
    var createdOn: NSDate = NSDate()
}

class ToDoList: JSONModel {
    var items: [ToDoItem] = []
}

我可以通过调用toJSONString()ToDoItem转换为JSON,但是同一方法不适用于ToDoList,它返回nil.知道为什么会这样吗?

I can convert a ToDoItem to JSON by calling toJSONString() but the same method doesn't work with ToDoList, it returns nil. Any idea why is this happening?

推荐答案

由于与Obj-C运行时支持的反射不兼容,JSONModel不支持Swift. JSONModel当前需要此反射功能,以便正确解析类型. 我们正在研究定义类型映射的替代方法.

JSONModel does not support Swift due to incompatibilities with the reflection supported by the Obj-C runtime. This reflection ability is currently required by JSONModel in order to resolve types correctly. We are looking into alternative methods of defining the type mappings though.

具体来说,JSONModel依赖于使用协议来确定集合类型(如字典,数组等)中项目的类型.在Swift中定义的协议在运行时不可见-阻止JSONModel正确反序列化集合类型.

Specifically, JSONModel relies on the use of protocols to determine the type of items in collection types, such as dictionaries, arrays, etc. Protocols defined in Swift are not visible at runtime - preventing JSONModel from deserializing collection types correctly.

目前,您有两种选择:

  1. 从JSONModel切换到另一个支持Swift的JSON(反序列化)库
  2. 在Objective-C中定义模型

我知道这不是理想的选择,但恐怕目前的JSONModel行为无法解决.

I know this isn't ideal, but I'm afraid a workaround is not possible with the current JSONModel behavior.

这篇关于JSONModel无法与Swift数组一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆