您看到此错误是因为编译器无法推断Optional 变量users 的类型,这些变量传递给以下函数,这些函数适用于泛型并且需要能够推断类型。
Swift 中的Optional 实际实现如下所示。我猜如果Optional 可能是nil aka .none,编译器无法推断方法的类型,例如items 和 bind(to:) 适用于泛型。
public enum Optional<Wrapped> : ExpressibleByNilLiteral {
/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
/// Creates an instance that stores the given value.
public init(_ some: Wrapped)
//...
}
解决方法 1.):您可以使用 filterNil() (RxOptionals lib) 来避免该问题。
private func bind() {
users.asObservable().filterNil().bind(to:
tableView.rx.items(cellIdentifier: "UserCell",
cellType: UITableViewCell.self)) { (index, user, cell) in
// Cell setup.
}.disposed(by: disposeBag)
}
解决方法 2.):将 users 设为非可选。如果您没有用户,只需将一个空数组设置为值。
let users: Variable<[User]> = Variable<[User]>([])
解决方法 3.):在 map 函数中使用 Nil-Coalescing Operator ?? 类似
private func bind() {
users.asObservable().map { optionalUsers -> [User] in
return optionalUsers ?? []
}
.bind(to:
tableView.rx.items(cellIdentifier: "UserCell",
cellType: UITableViewCell.self)) { (index, user, cell) in
// Cell setup.
}.disposed(by: disposeBag)
}
旁注:Variable 在最新版本的 RxSwift 中已弃用
仅供参考:
items的实现
public func items<S: Sequence, Cell: UITableViewCell, O : ObservableType>
(cellIdentifier: String, cellType: Cell.Type = Cell.self)
-> (_ source: O)
-> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void)
-> Disposable
where O.E == S {
return { source in
return { configureCell in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S> { (tv, i, item) in
let indexPath = IndexPath(item: i, section: 0)
let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.items(dataSource: dataSource)(source)
}
}
}
bind(to:)的实现
public func bind<O: ObserverType>(to observer: O) -> Disposable where O.E == E {
return self.subscribe(observer)
}