[英]How do I get the correct value from onNext in RxSwift?
我已parsed
JSON
从数据URL
和subscriber
在array
触发相应的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
返回MyProject.People
但应该给出字符串。 我试过arrayData.name
和arrayData.value.name
但它没有显示任何内容。 People
看起来像这样:
class People {
var name = ""
var job = ""
}
我建议您使用Codable
协议而不是JSON
pod。 您可以在此处阅读有关Codable
更多信息: https : 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] 数组,不允许直接访问 people 属性(姓名、工作)。 您必须从特定索引中获取人员,然后才能访问人员的财产。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.