sindresorhus / Defaults

💾 Swifty and modern UserDefaults
https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults
MIT License
1.97k stars 117 forks source link

Validate the default key name #120

Closed sindresorhus closed 1 year ago

sindresorhus commented 1 year ago

In the next major version, we should strictly validate the key name to ensure users don't accidentally make the key's unable to be observed.

The rules are as follows:

The key must be ASCII, not start with @, and cannot contain a dot (.).

hank121314 commented 1 year ago

I think we might have three ways to do it.

  1. Mark Defaults.Key initializer as throws:

    • pros:
      1. Can throw an error early when user input an invalid name.
    • cons:
      1. Need to add try when initialize Defaults.Key.
  2. Add an assertion in Defaults.Key initializer:

    • pros:
      1. No need to add try.
    • cons:
      1. Assertion is not available in release mode.
  3. Mark KVO related function(ex. Defaults.observe) as throws:

    • pros:
      1. No need to add try.
sindresorhus commented 1 year ago

Only 2. is really feasible.

The question is, do assertions work when they are in a package and you build your app in debug mode.

sindresorhus commented 1 year ago

Actually, a better solution could be to show a warning in Xcode using this hack: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Internal/RuntimeWarnings.swift

hank121314 commented 1 year ago

Actually, a better solution could be to show a warning in Xcode using this hack: pointfreeco/swift-composable-architecture@main/Sources/ComposableArchitecture/Internal/RuntimeWarnings.swift

This looks awesome! Will try to implement this in Defaults.