Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Swift] namespacing for better domain management #46

Open
vinhnx opened this issue Sep 12, 2017 · 0 comments
Open

[Swift] namespacing for better domain management #46

vinhnx opened this issue Sep 12, 2017 · 0 comments

Comments

@vinhnx
Copy link
Owner

vinhnx commented Sep 12, 2017

Say we want write custom logic for a specific domain. For example: below, I have a UUID getter and setter.

We could add a nested enum/struct for AppUUID.

import KeychainAccess

final class KeychainHelper {
    
    // MARK: - Public
    
    static func nxv_store(_ value: String, key: String) {
        let keychain = Keychain(service: "\(AppConfiguration.App.bundleID).\(key)")
        keychain[key] = value
    }
    
    static func nxv_valueForKey(_ key: String) -> String {
        let keychain = Keychain(service: "\(AppConfiguration.App.bundleID).\(key)")
        return keychain[key] ?? ""
    }
}

extension KeychainHelper {
    
    // MARK: - UUID
    
    struct AppUUID {
        static func generateAppUUIDandStore() {
            // only generate and store UUID on when we can't get UUID from keychain,
            // since we store it to keychain, so don't check for first launch
            if isAppUUIDValid == false {
                KeychainHelper.nxv_store(UUID().uuidString, key: Constants.Keychain.savedAppUUID)
            }
        }
        
        static var appUUID: String {
            return KeychainHelper.nxv_valueForKey(Constants.Keychain.savedAppUUID)
        }
        
        static var isAppUUIDValid: Bool {
            return appUUID.isEmpty == false
        }
    }
}

So in usage, it's better to know on glance which problem we are dealing from the helper

let appUUID = KeychainHelper.AppUUID.appUUID

// is, in my opinion, better than

let appUUID = KeychainHelper.appUUID

As we glance it, we could see that we are telling KeychainHelper, return me a generated appUUID from AppUUID domain.

We could just declare struct UUID, but thanks to Swift compiler warning, in the setter, we use Foundation's UUID class method UUIDString to generate a unique ID. So namespace collision happened there.

TIL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant