解码RealmSwift类中的可选对象列表

时间:2019-06-20 09:08:52

标签: swift list realm codable

我正在尝试初始化Realm类中的对象的Codable List,问题是服务器返回空列表时应用程序崩溃了

这是初始化列表的代码

class TicketDetails: Object, Decodable {

    var working: [WorkingHour]?
    var workingHours = List<WorkingHour>()

    public convenience required init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let workingArray = try container.decodeIfPresent(Array<WorkingHour>.self, forKey: .working) {
            working = workingArray
            workingHours.append(objectsIn: workingArray)
        } else {
            working = nil
            workingHours = List.init()
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这里有些奇怪。

TicketDetails被声明为Realm对象,但包含一个数组,该数组只是Realm List属性的副本。为什么?卸下阵列。列表需要放任其所有,并删除整个else子句,否则将不起作用。

class TicketDetails: Object, Decodable 
{
  let workingHours = List<WorkingHour>()

  public convenience required init(from decoder: Decoder) throws {
    self.init()
    let container = try decoder.container(keyedBy: CodingKeys.self)
    if let workingArray = try container.decodeIfPresent(Array<WorkingHour>.self, forKey: .working) 
    {
        workingHours.append(objectsIn: workingArray)
    }
  }
}

答案 1 :(得分:0)

最新版本的RealmCocoa 4.4.1提供了更方便,更有效的解决方案。如果网络响应与您的模型不同,请不要忘记定义CodingKeys枚举。

times = int(input())
for num in range(times):
    n = input()
    n = str(n)
    if len(n) == 1:
        print('YES')
    else:
        if len(n) % 2 == 0:
            list2 = []
            list3 = []    
            for i in range(int(len(n)//2)):
                list2.append(n[i])
                list3.append(n[int(len(n)//2)+i])
            if sorted(list2)==sorted(list3):
                print('YES')
            else:
                print('NO')

        else:

            string_list = [n[:len(n)//2], n[len(n)//2+1:]]
            if sorted(string_list[0]) == sorted(string_list[1]):
                print('YES')
            else:
                print('NO')