嗨,我尝试学习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]
        ]
    }

}

最佳答案

DummyUser模型中,您使用的是失败的初始化程序,因此,如果为init方法提供的词典错误,它将返回nil
compactMap自动自动过滤nil,这就是您的输出为空的原因。

看这段代码:

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

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

07-27 19:00