Crear funciones de consulta personalizadas con rutas clave





, , Swift , . , , key paths, function/result builders . ., Swift .





, , , , . - «-DSL», , .





key paths

, , , , (Article



):





struct Article {
    var title: String
    var body: String
    var category: Category
    var isRead: Bool
    ...
    
}
      
      







, , . - , key path Swift , , isRead



:





let articles: [Article] = ...
let readArticles = articles.filter(\.isRead)
      
      



, , true



- , , , ( ):





let unreadArticles = articles.filter { !$0.isRead }
      
      



, , , , : « , key path ? "





. , , key path , true



false



:





prefix func !<T>(keyPath: KeyPath<T, Bool>) -> (T) -> Bool {
    return { !$0[keyPath: keyPath] }
}
      
      







, , !



, Bool



key path, , ( ) , , , unreadArticles



:





let unreadArticles = articles.filter(!\.isRead)
      
      



, , !



, , - .





key paths

  key paths , Equatable



. , , , Equatable



(category



) . , Category



, enum, :





extension Article {
    enum Category {
        case fullLength
        case quickReads
        case basics
        ...
    }
}
      
      







, !



key path , ==



, , , Bool



, API filter



:





func ==<T, V: Equatable>(lhs: KeyPath<T, V>, rhs: V) -> (T) -> Bool {
    return { $0[keyPath: lhs] == rhs }
}
      
      



, key path, :





let fullLengthArticles = articles.filter(\.category == .fullLength)
      
      



, , , Swift , , . , - , , , - Swift. , , .





, , Swift Sundell, . , , , , .





, « Swift» Twitter .






"IOS Developer. Professional".





  • iOS- ?





  • -?





  • , ?





  • , ?





, , - . . .












All Articles