我正在使用 RxSwift 和 Moya。我正进入(状态
致命错误:在展开可选值时意外发现 nil
authors.map {...
tableViewController中的行错误。当我打印时authors
,我发现它是零。而且我找不到问题出在哪里。我正在使用 Moya-ObjectMapper/RxSwift 库。在最新版本中缺少 Observable+Objectmapper.swift 文件,所以我在 github 上找到并替换了它。
//import libraries
class AuthorsTableViewController: UITableViewController {
var viewModel: AuthorsViewModelType!
var authors: Driver<RequestResult<[Author]>>!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setUpBindings()
}
func setUpBindings() {
tableView.dataSource = nil
tableView.delegate = nil
authors.map { result -> [Author] in ---> Here
...
}.disposed(by: disposeBag)
}
}
我的视图模型:
//import libraries
public protocol AuthorsViewModelType {
func getAuthors(destination: YazarAPI) -> Driver<RequestResult<[Author]>>
}
public class AuthorsViewModel: AuthorsViewModelType {
fileprivate var provider = YazarAPI.sharedProviderInstance
public func getAuthors(destination: YazarAPI) -> Driver<RequestResult<[Author]>> {
return provider.request(destination)
.observeOn(MainScheduler.instance)
.filterSuccessfulStatusCodes()
.mapAuthors(destination: destination)
.map { .Success($0) }
.asDriver(onErrorRecover: { error in
return .just(.Error(ReqestError(description: error.localizedDescription, code: .requestError)))
})
}
}
private extension Observable where E == Response {
func mapAuthors(destination: YazarAPI) -> Observable<[Author]> {
let authors: Observable<[Author]>
switch destination {
case .authors:
authors = self.mapObject(Authors.self).map { $0.authors ?? [] }
default:
fatalError("Unexpected request type \"\(destination)\"")
}
return authors
}
}