jun*_*cia 2 generics optional ios swift rx-swift
我有一个UITableView和一个users变量,其签名如下:
let users: Variable<[User]?> = Variable<[User]?>(nil)
Run Code Online (Sandbox Code Playgroud)
当我试图在UITableView中绑定这个用户数组时,我收到了错误Generic parameter 'Self' could not be inferred.这只发生在我观察Optional类型时.为什么会这样?这种情况的解决方法是什么?
这是我正在做的一个例子:
private func bind() {
// Does not compile: Generic parameter 'Self' could not be inferred
users.asObservable().bind(to:
tableView.rx.items(cellIdentifier: "UserCell",
cellType: UITableViewCell.self)) { (index, user, cell) in
// Cell setup.
}.disposed(by: disposeBag)
}
Run Code Online (Sandbox Code Playgroud)
您会看到此错误,因为编译器无法推断传递给以下函数的Optional变量类型,这些users函数适用于泛型并且需要能够推断出类型.
一个Optional在夫特被实际实现,如下所示.我想在的情况下,Optional是有可能nil又名.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)
//...
}
Run Code Online (Sandbox Code Playgroud)
解决方法1.):你可以使用filterNil()(RxOptionalslib)来避免这个问题.
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)
}
Run Code Online (Sandbox Code Playgroud)
解决方法2.):使users非可选.如果您没有用户,只需将空数组设置为值.
let users: Variable<[User]> = Variable<[User]>([])
Run Code Online (Sandbox Code Playgroud)
解决方法3.):在函数中使用Nil-Coalescing运算符 ??map
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)
}
Run Code Online (Sandbox Code Playgroud)
旁注: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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
实施 bind(to:)
public func bind<O: ObserverType>(to observer: O) -> Disposable where O.E == E {
return self.subscribe(observer)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2880 次 |
| 最近记录: |