Swift Compact Map返回空

时间:2018-06-24 07:49:26

标签: ios iphone swift functional-programming rx-swift

嗨,我正在尝试学习RXSwift,并且第一次遇到诸如Maps和Compact Maps这样的概念。

我能够得到响应,但是这一行总是返回空。

  

objects.compactMap(DummyUser.init)

fileprivate let Users = Variable<[DummyUser]>([])
    fileprivate let bag = DisposeBag()



response
                .filter { response, _ in
                    return 200..<300 ~= response.statusCode
                }
                .map { _, data -> [[String: Any]] in
                    guard (try? JSONSerialization.jsonObject(with: data, options: [])) != nil  else {
                            return []
                    }

                    let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]

                  //  print(json!["results"])
                    return json!["results"] as! [[String : Any]]
                }
                .filter { objects in
                    return objects.count > 0
                }
                .map { objects in
                  //  objects.forEach{print($0["name"]!)}
                    let names = objects.map { $0["name"]!}
                    print(names)
                    return objects.compactMap(DummyUser.init)
                }
                .subscribe(onNext: { [weak self] newEvents in
                    self?.processEvents(newEvents)
                })
                .disposed(by: bag)

func processEvents(_ newEvents: [DummyUser]) {
        var updatedEvents = newEvents + Users.value
        if updatedEvents.count > 50 {
            updatedEvents = Array<DummyUser>(updatedEvents.prefix(upTo: 50))
        }

        Users.value = updatedEvents
        DispatchQueue.main.async {
            self.MianUsertable.reloadData()
        }
     //   refreshControl?.endRefreshing()

        let eventsArray = updatedEvents.map{ $0.dictionary } as NSArray
        eventsArray.write(to: userFileURL, atomically: true)

    }

我的Json回应在这里

  

https://randomuser.me/api/?results=5

DummyUser类

import Foundation

typealias AnyDict = [String: Any]

class DummyUser {
    let gender: String
    let name: AnyDict
    let dob: String
    let picture: AnyDict

    init?(dictionary: AnyDict) {
        guard let Dgender = dictionary["gender"] as? String,
             let Dname = dictionary["name"] as? AnyDict,
             let birthdata = dictionary["dob"] as? AnyDict,
             let Ddob = birthdata["dob"] as? String,
             let Dpicture = dictionary["picture"] as? AnyDict
            else {
                return nil
        }

        gender = Dgender
        name = Dname
        dob = Ddob
        picture = Dpicture
    }



    var dictionary: AnyDict {
        return [
            "user": ["name" : name, "gender": gender, "dob": dob],
            "picture" : ["userImage": picture]
        ]
    }

}

1 个答案:

答案 0 :(得分:1)

在您的DummyUser模型中,您使用的是失败的初始化程序,因此,如果将错误的字典提供给init方法,它将返回nil

compactMap自动自动过滤nil,这就是输出为空的原因。

看这段代码:

let names = objects.map { $0["name"]!}
return objects.compactMap(DummyUser.init)

我将调试名为names的变量,因为它可能为DummyUser初始化程序输入了错误。它应该是包含所有DummyUser参数的字典。您还可以调试失败的初始化程序,以查看缺少哪个参数。