提问人:iOSGeek 提问时间:5/30/2020 最后编辑:iOSGeek 更新时间:5/31/2020 访问量:414
LazyMapSequence 在字符串数组除外时的用法
Usage of LazyMapSequence when an array of Strings is excepted
问:
我有一个 User 对象
@objc(User)
public class User: NSManagedObject {
@NSManaged public var firstname: String
@NSManaged public var lastname: String
@NSManaged public var country: String
@NSManaged public var friends: NSSet // of User objects
var full: String {
firstname + " " + lastname
}
var friendsArray: [User] {
friends.allObjects as? [User] ?? []
}
}
在某些时候,我想将大量用户(80k 对象)映射到一组 View 模型
struct ItemViewModel: Hashable {
let id: UUID
let friendsName: [String]
}
没有懒惰需要很长时间,所以我选择了懒惰的usag:
func prepareViewModel(users: [User]) -> [ItemViewModel] {
users.map { user in
let friendsName = user.friendsArray.lazy.filter{["en", "fr"].contains($0.country)}.map(\.full)
return ItemViewModel(id: UUID(), friendsName: friendsName)
}
}
但是我收到一个错误:
Cannot convert value of type 'LazyMapSequence<LazyFilterSequence<LazySequence<[User]>.Elements>.Elements, String>'
(aka 'LazyMapSequence<LazyFilterSequence<Array<User>>, String>') to expected argument type '[String]'
这是有道理的,因为现在朋友的名字数组稍后会被懒惰地处理。我试图将视图模型结构转换为保持:
struct ItemViewModel: Hashable {
let id: UUID
let friendsName: LazyMapSequence<LazyFilterSequence<[User]>, String>
}
但是现在没有办法在使用 as type 时保持自动一致性,以及有关如何提高逻辑性能的任何提示Hashable
Hashable
LazyMapSequence<LazyFilterSequence<[User]>, String>
ItemViewModel
答: 暂无答案
上一个:可跨步日期
评论
user.friendsArray.lazy.filter{["en", "fr"].contains($0.country)}.map(\.full)
friendsName