文章40 | 阅读 19064 | 点赞0
struct Article {
let id: UUID
let source: URL
let title: String
let body: String
}
let articleIDs = articles.map { $0.id }
let articleSources = articles.map { $0.source }
extension Sequence {
func map<T>(_ keyPath: KeyPath<Element, T>) -> [T] {
return map { $0[keyPath: keyPath] }
}
}
let articleIDs = articles.map(\.id)
let articleSources = articles.map(\.source)
extension Sequence {
func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] {
return sorted { a, b in
return a[keyPath: keyPath] < b[keyPath: keyPath]
}
}
}
playlist.songs.sorted(by: \.name)
playlist.songs.sorted(by: \.dateAdded)
playlist.songs.sorted(by: \.ratings.worldWide)
struct SongCellConfigurator {
func configure(_ cell: UITableViewCell, for song: Song) {
cell.textLabel?.text = song.name
cell.detailTextLabel?.text = song.artistName
cell.imageView?.image = song.albumArtwork
}
}
struct CellConfigurator<Model> {
let titleKeyPath: KeyPath<Model, String>
let subtitleKeyPath: KeyPath<Model, String>
let imageKeyPath: KeyPath<Model, UIImage?>
func configure(_ cell: UITableViewCell, for model: Model) {
cell.textLabel?.text = model[keyPath: titleKeyPath]
cell.detailTextLabel?.text = model[keyPath: subtitleKeyPath]
cell.imageView?.image = model[keyPath: imageKeyPath]
}
}
let songCellConfigurator = CellConfigurator<Song>(
titleKeyPath: \.name,
subtitleKeyPath: \.artistName,
imageKeyPath: \.albumArtwork
)
let playlistCellConfigurator = CellConfigurator<Playlist>(
titleKeyPath: \.title,
subtitleKeyPath: \.authorName,
imageKeyPath: \.artwork
)
class ListViewController {
private var items = [Item]() { didSet { render() } }
func loadItems() {
loader.load { [weak self] items in
self?.items = items
}
}
}
func setter<Object: AnyObject, Value>(
for object: Object,
keyPath: ReferenceWritableKeyPath<Object, Value>
) -> (Value) -> Void {
return { [weak object] value in
object?[keyPath: keyPath] = value
}
}
class ListViewController {
private var items = [Item]() { didSet { render() } }
func loadItems() {
loader.load(then: setter(for: self, keyPath: \.items))
}
}
// This extension will let us group any Sequence (such as an
// Array or a Set), based on a given key path.
extension Sequence {
func grouped<T: Hashable>(by keyPath: KeyPath<Element, T>) -> [T: [Element]] {
// Using key path subscripting syntax, we can dynamically
// access a member of a type based on a key path.
return .init(grouping: self, by: { $0[keyPath: keyPath] })
}
}
func scan(_ string: String, using matchers: [Matcher]) {
// The result is that our call sites become really clean, since
// we can simply use a key path literal to group any sequence.
let matchersByPattern = (
start: matchers.grouped(by: \.pattern.start),
end: matchers.grouped(by: \.pattern.end)
)
...
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/Forever_wj/article/details/120951920
内容来源于网络,如有侵权,请联系作者删除!