如何从 RxSwift 中的 onNext 获取正确的值?

How do I get the correct value from onNext in RxSwift?

我有来自 URLparsed JSON 数据和 array 上的 subscriber 触发器相应地填充了 array .但我从 onNext 获得的数据如下所示:MyProject.People。我如何获得实际值?这是我的代码:

guard let myURL = URL(string: "https://api.myjson.com/bins/e5gjk") else { return }
var myArray: Variable<[People]> = Variable([])

myArray.asObservable().subscribe(onNext: { arrayData in
    print("TRIGGERED", arrayData)

    }).disposed(by: bag)

Alamofire.request(myURL, method: .get)
    .validate()
    .responseJSON{ response in

    guard response.result.isSuccess else {
       print("Error")
       return
    }

    let json = JSON(response.result.value)

    for i in 0...json["employees"].count {
        let people = People()
        people.name = json["employees"][i]["firstName"].stringValue
         people.job = json["employees"][i]["job"].stringValue

         myArray.value.append(people)
    }

    for i in myArray.value {
        print(i.name)
        print(i.job)
    }
}

所以,arrayData returns MyProject.People 但应该给出字符串。我试过 arrayData.namearrayData.value.name 但它没有显示任何内容。 People 看起来像这样:

class People {
    var name = ""
    var job = ""
}

我会建议你使用Codable协议而不是JSON pod。 您可以在此处阅读有关 Codable 的更多信息:https://www.swiftbysundell.com/basics/codable/

有关 CustomStringConvertible 的更多信息,请点击此处: https://developer.apple.com/documentation/swift/customstringconvertible

这可以这么简单:

class Employees: Codable {
    let employees: [Employee]
}

/// If you want to print array with values
/// A textual representation of this instance.
extension Employees: CustomStringConvertible {
    var description: String {
        var text = ""
        for employee in employees {
            text += "Employee first name: \(employee.firstName), Job: \(employee.job)\n"
        }
        return text
    }
}

class Employee: Codable {
    let firstName: String
    let job: String
}

我也尝试了简单的 request 并成功完成,我能够获得所有实体:(您可以将 Alamofire 响应从 responseJSON 更改为responseData)

let employees = try! JSONDecoder().decode(Employees.self, from: response.data)
print(employees)
...
Employee first name: Jocke, Job: developer
Employee first name: Anna, Job: construction
Employee first name: Peter, Job: pilot

myArray.value 是 [People] 的数组,不允许直接访问人 属性(姓名、工作)。您必须从特定索引中获取人员,然后才能访问人员的 属性。