πŸ”Œ Enum key paths

Overview

πŸ”Œ Enum key paths

With the package you can use key paths with enums

import EnumKeyPaths

// MARK: - Authentication

enum Authentication {
    case authenticated(accessToken: String)
    case unauthenticated
}

/Authentication.authenticated // EnumKeyPath
   

user[keyPath: \User.id] = 113
user[keyPath: \User.id] // 113

let authentication = (/Authentication.authenticated).embed("access")
(/Authentication.authenticated).extract(from: authentication) // Optional("access")

Extraction can fail and return nil because the cases may not match up.

(/Authentication.authenticated).extract(from: .unauthenticated) // nil

Swift key paths use dot-syntax to dive deeper into a structure, enum key paths use a double-dot syntax:

\Table.user.name
// WritableKeyPath
   

/Result<Authentication, Error>..Authentication.authenticated
// EnumKeyPath
   
    
     , String>
    
   

Enum key paths provide an "identity" path, which is useful for interacting with APIs that use key paths but you want to work with entire structure.

\User.self           // WritableKeyPath
   
/Authentication.self // EnumKeyPath
   

Key paths are created for every property, even computed ones, so what is the equivalent for enum key paths? "computed" enum key paths can be created by providing custom embed and extract functions:

EnumKeyPath<Authentication, String>(
    embed: { token in
        Authentication.authenticated(token: encrypt(token))
    },
    extract: { authentication in
        guard
            case let .authenticated(encryptedToken) = authentication,
            let decryptedToken = decrypt(token)
            else { return nil }
        return decryptedToken
    }
)

Since Swift 5.2, key path expressions can be passed directly to methods like map. The same is true of enum key path expressions, which can be passed to methods like compactMap:

users.map(\User.name)
authentications.compactMap(/Authentication.authenticated)

Ergonomic associated value access

EnumKeyPaths uses Swift reflection to automatically and extract associated values from any enum in a single, short expression. This helpful utility is made available as a public module function that can be used in your own libraries and apps:

extract(case: Authentication.authenticated, from: .authenticated("token"))
// Optional("token")

Enum key paths operators

// With operators:
/Authentication.authenticated
// Without:
EnumKeyPath.case(Authentication.authenticated)

// With operators:
authentications.compactMap(/Authentication.authenticated)
// Without:
authentications.compactMap(extract(Authentication.authenticated))

// With operators:
/Result<Authentication, Error>.success..Authentication.authenticated
// Without:
EnumKeyPath.case(Result<Authentication, Error>.success)
  .appending(path: .case(Authentication.authenticated))

// With operators:
/Authentication.self
// Without operators:
EnumKeyPath<Authentication, Authentication>.self

Installation

You can add EnumKeyPaths to an Xcode project by adding it as a package dependency: https://github.com/Incetro/enum-key-paths

If you want to use EnumKeyPaths in a SwiftPM project, it's as simple as adding a dependencies clause to your Package.swift:

dependencies: [
    .package(url: "https://github.com/Incetro/enum-key-paths.git", from: "0.0.1")
]

License

All modules are released under the MIT license. See LICENSE for details.

You might also like...
Cachyr A typesafe key-value data cache for iOS, macOS, tvOS and watchOS written in Swift.

Cachyr A typesafe key-value data cache for iOS, macOS, tvOS and watchOS written in Swift. There already exists plenty of cache solutions, so why creat

πŸ’Ύ Safe, statically-typed, store-agnostic key-value storage written in Swift!

Storez πŸ’Ύ Safe, statically-typed, store-agnostic key-value storage Highlights Fully Customizable: Customize the persistence store, the KeyType class,

SwiftStore - Key/Value store for Swift backed by LevelDB.

SwiftStore Key/Value store for Swift backed by LevelDB. Usage Create instances of store import SwiftStore

Modern thread-safe and type-safe key-value observing for Swift and Objective-C

Now Archived and Forked PMKVObserver will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork o

πŸŽ‰ WWDC 2021 Swift Student Challenge Winner πŸŽ‰ Dance Party allows users to record choreography and play against other users to try and match the key poses!
πŸŽ‰ WWDC 2021 Swift Student Challenge Winner πŸŽ‰ Dance Party allows users to record choreography and play against other users to try and match the key poses!

πŸ’ƒ Dance Party πŸ•Ί 🍎 WWDC 2021 Swift Student Challenge Winner πŸŽ‰ Installation Steps (Works on iPad Only) Clone or Download Unzip the .playgroundbook.z

iPhone and iPod Touch version of Skeleton Key: is an addictive and unique puzzle game in which you shift keys around the board unlocking treasure chests. Made with cocos2d-iphone.

Skeleton Key (iOS) Skeleton Key is an addictive and unique puzzle game in which you shift keys around the board unlocking treasure chests. It's availa

YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.
YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.

YapDatabase is a collection/key/value store and so much more. It's built atop sqlite, for Swift & Objective-C developers, targeting macOS, iOS, tvOS &

πŸ’Ύ Safe, statically-typed, store-agnostic key-value storage written in Swift!

Storez πŸ’Ύ Safe, statically-typed, store-agnostic key-value storage Highlights Fully Customizable: Customize the persistence store, the KeyType class,

An Objective-C wrapper for RocksDB - A Persistent Key-Value Store for Flash and RAM Storage.

ObjectiveRocks ObjectiveRocks is an Objective-C wrapper of Facebook's RocksDB - A Persistent Key-Value Store for Flash and RAM Storage. Current RocksD

Key-Value store for Swift backed by LevelDB

SwiftStore Key/Value store for Swift backed by LevelDB. Usage Create instances of store import SwiftStore // Create a store. let store = SwiftStore(s

A protocol-centric, type and queue safe key-value workflow.
A protocol-centric, type and queue safe key-value workflow.

Light-weight, strict protocol-first styled PropertyKit helps you to easily and safely handle guaranteed values, keys or types on various situations of

An efficient, small mobile key-value storage framework developed by WeChat. Works on Android, iOS, macOS, Windows, and POSIX.
An efficient, small mobile key-value storage framework developed by WeChat. Works on Android, iOS, macOS, Windows, and POSIX.

δΈ­ζ–‡η‰ˆζœ¬θ―·ε‚ηœ‹θΏ™ι‡Œ MMKV is an efficient, small, easy-to-use mobile key-value storage framework used in the WeChat application. It's currently available on Andr

AppKit Carbon key codes to UIKey-compatible enums

KeyCodes Versions of UIKey, UIKeyboardHIDUsage, and UIKeyModifierFlags that work with AppKit's NSEvent. No need for Carbon.HIToolbox. Aside from being

Easy JSON to NSObject mapping using Cocoa's key value coding (KVC)
Easy JSON to NSObject mapping using Cocoa's key value coding (KVC)

#Motis Object Mapping Easy JSON to NSObject mapping using Cocoa's key value coding (KVC) Motis is a user-friendly interface with Key Value Coding that

Key-Value Coding (KVC) for native Swift classes and structs

SwiftKVC SwiftKVC brings key-value coding to native Swift classes and structures. You can easily set and access properties just using a subscript: var

A really simple key-value wrapper for keychain.

PlainKeychain A really simple key-value wrapper for keychain. Features βœ… Key-value pairs using kSecClassGenericPassword. ❌ Internet passwords (kSecCla

A key value store for storing per-developer environment and application keys

A key value store for enviroment and application keys. Its good security practice to keep production keys out of developer hands. CocoaPods-keys makes

RSA public/private key generation, RSA, AES encryption/decryption, RSA sign/verify in Swift with CommonCrypto in iOS and OS X

SwCrypt Create public and private RSA keys in DER format let (privateKey, publicKey) = try! CC.RSA.generateKeyPair(2048) Convert them to PEM format l

RSA public/private key encryption in Swift

SwiftyRSA Maintainer(s): @ikeith Public key RSA encryption in Swift. SwiftyRSA is used in the Scoop iOS app to encrypt driver license numbers before s

Owner
Incetro
Incetro
JSEN (JSON Swift Enum Notation) is a lightweight enum representation of a JSON, written in Swift.

JSEN /ˈdΚ’eΙͺsΙ™n/ JAY-sΙ™n JSEN (JSON Swift Enum Notation) is a lightweight enum representation of a JSON, written in Swift. A JSON, as defined in the EC

Roger Oba 8 Nov 22, 2022
RSA public/private key encryption, private key signing and public key verification in Swift using the Swift Package Manager. Works on iOS, macOS, and Linux (work in progress).

BlueRSA Swift cross-platform RSA wrapper library for RSA encryption and signing. Works on supported Apple platforms (using Security framework). Linux

Kitura 122 Dec 16, 2022
RSA public/private key encryption, private key signing and public key verification in Swift using the Swift Package Manager. Works on iOS, macOS, and Linux (work in progress).

BlueRSA Swift cross-platform RSA wrapper library for RSA encryption and signing. Works on supported Apple platforms (using Security framework). Linux

Kitura 122 Dec 16, 2022
🎯 PredicateKit allows Swift developers to write expressive and type-safe predicates for CoreData using key-paths, comparisons and logical operators, literal values, and functions.

?? PredicateKit PredicateKit is an alternative to NSPredicate allowing you to write expressive and type-safe predicates for CoreData using key-paths,

Faiçal Tchirou 352 Jan 3, 2023
Convert your own struct/enum to AnyObject easily.

AnyObjectConvertible Convert your own struct/enum to AnyObject easily. Sumally We can cast everything as AnyObject at Swift3.0 ?? So, we would not nee

tarunon 62 Feb 2, 2022
Parsing indeterminate types with Decodable and Either enum using Swift

Decodable + Either Parsing indeterminate types with Decodable and Either enum us

Alonso Alvarez 1 Jan 9, 2022
SFSymbols SwiftUI Enum

SF SFSymbols SwiftUI Enum Example: All lines are equivalent. Image(systemName: "square.fill.and.line.vertical.square.fill") Image(systemName:

Zach Eriksen 34 Oct 24, 2022
An iOS library to route API paths to objects on client side with request, mapping, routing and auth layers

WANetworkRouting Developed and Maintained by ipodishima Founder & CTO at Wasappli Inc. Sponsored by Wisembly A routing library to fetch objects from a

null 10 Nov 20, 2022
COVID Safe Paths (based on Private Kit) is an open and privacy preserving system to use personal information to battle COVID

COVID Safe Paths is a mobile app for digital contract tracing (DCT) sponsored by Path Check a nonprofit and developed by a growing global community of engineers, designers, and contributors. Safe Paths is based on research originally conducted at the MIT Media Lab.

PathCheck Foundation 470 Nov 6, 2022
Mac App Store: Embedding a Command Line tool using paths as arguments

Mac App Store: Embedding a Command Line tool using paths as arguments Code snippets to embed a Command Line tool using paths as arguments on the Mac A

Alexandre Colucci 10 Aug 20, 2022