├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ └── swift.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Package.swift ├── README.md ├── SECURITY.md ├── Sources ├── PrivacyInfo.xcprivacy └── UserDefaults │ ├── DefaultKeys.swift │ ├── Protocols │ ├── AnyOptional.swift │ └── DefaultsCustomDataType.swift │ ├── UserDefaults.swift │ └── extension │ └── ArrayExtension.swift └── Tests └── UserDefaultsTests └── UserDefaultsTests.swift /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: EngOmarElsayed 4 | 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/swift.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Swift project 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-swift 3 | 4 | name: Swift 5 | 6 | on: 7 | push: 8 | branches: [ "main" ] 9 | pull_request: 10 | branches: [ "main" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: macos-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Build 20 | run: swift build -v 21 | - name: Run tests 22 | run: swift test -v 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | eng.omar.elsayed@hotmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to SwiftUserDefaults 2 | 3 | A big welcome and thank you for considering contributing to SwiftUserDefaults open source projects! 4 | 5 | Reading and following these guidelines will help us make the contribution process easy and effective for everyone involved. It also communicates that you agree to respect the time of the developers managing and developing these open source projects. In return, we will reciprocate that respect by addressing your issue, assessing changes, and helping you finalize your pull requests. 6 | 7 | ## Quicklinks 8 | 9 | * [Code of Conduct](#code-of-conduct) 10 | * [Getting Started](#getting-started) 11 | * [Issues](#issues) 12 | * [Pull Requests](#pull-requests) 13 | * [Getting Help](#getting-help) 14 | 15 | ## Code of Conduct 16 | 17 | We take our open source community seriously and hold ourselves and other contributors to high standards of communication. By participating and contributing to this project, you agree to uphold our [Code of Conduct](https://github.com/EngOmarElsayed/SwiftUserDefaults/blob/main/CODE_OF_CONDUCT.md). 18 | 19 | ## Getting Started 20 | 21 | Contributions are made to this repo via Issues and Pull Requests (PRs). A few general guidelines that cover both: 22 | 23 | - To report security vulnerabilities, please use our [Responsible Disclosure Program](https://auth0.com/whitehat) which is monitored by our security team. 24 | - Search for existing Issues and PRs before creating your own. 25 | - We work hard to makes sure issues are handled in a timely manner but, depending on the impact, it could take a while to investigate the root cause. A friendly ping in the comment thread to the submitter or a contributor can help draw attention if your issue is blocking. 26 | 27 | ### Issues 28 | 29 | Issues should be used to report problems with the library, request a new feature, or to discuss potential changes before a PR is created. When you create a new Issue, a template will be loaded that will guide you through collecting and providing the information we need to investigate. 30 | 31 | If you find an Issue that addresses the problem you're having, please add your own reproduction information to the existing issue rather than creating a new one. Adding a [reaction](https://github.blog/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/) can also help be indicating to our maintainers that a particular problem is affecting more than just the reporter. 32 | 33 | ### Pull Requests 34 | 35 | PRs to our libraries are always welcome and can be a quick way to get your fix or improvement slated for the next release. In general, PRs should: 36 | 37 | - Only fix/add the functionality in question **OR** address wide-spread whitespace/style issues, not both. 38 | - Add unit or integration tests for fixed or changed functionality (if a test suite already exists). 39 | - Address a single concern in the least number of changed lines as possible. 40 | - Include documentation in the repo. 41 | - Be accompanied by a complete Pull Request template (loaded automatically when a PR is created). 42 | 43 | For changes that address core functionality or would require breaking changes (e.g. a major release), it's best to open an Issue to discuss your proposal first. This is not required but can save time creating and reviewing changes. 44 | 45 | In general, we follow the ["fork-and-pull" Git workflow](https://github.com/susam/gitpr) 46 | 47 | 1. Fork the repository to your own Github account 48 | 2. Clone the project to your machine 49 | 3. Create a branch locally with a succinct but descriptive name 50 | 4. Commit changes to the branch 51 | 5. Following any formatting and testing guidelines specific to this repo 52 | 6. Push changes to your fork 53 | 7. Open a PR in our repository and follow the PR template so that we can efficiently review the changes. 54 | 55 | ## Getting Help 56 | 57 | Email Me at eng.omar.elsayed@hotmail.com. 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Eng.Omar Elsayed 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.7 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "UserDefaults", 8 | platforms: [ 9 | .iOS(.v14), 10 | .macOS(.v12), 11 | .watchOS(.v5), 12 | .tvOS(.v12) 13 | ], 14 | products: [ 15 | .library( 16 | name: "UserDefaults", 17 | targets: ["UserDefaults"]), 18 | ], 19 | targets: [ 20 | .target( 21 | name: "UserDefaults"), 22 | .testTarget( 23 | name: "UserDefaultsTests", 24 | dependencies: ["UserDefaults"]), 25 | ] 26 | ) 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SwiftUserDefaults 2 | ![example workflow](https://github.com/EngOmarElsayed/SwiftUserDefaults/actions/workflows/swift.yml/badge.svg) 3 | ![GitHub License](https://img.shields.io/github/license/EngOmarElsayed/SwiftUserDefaults) 4 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2FEngOmarElsayed%2FSwiftUserDefaults%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/EngOmarElsayed/SwiftUserDefaults) 5 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2FEngOmarElsayed%2FSwiftUserDefaults%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/EngOmarElsayed/SwiftUserDefaults) 6 | [![SPM compatible](https://img.shields.io/badge/SPM-compatible-4BC51D.svg?style=flat)](#swift-package-manager) 7 | 8 | ## Table of Contents 9 | 1. [Introduction](#introduction) 10 | 2. [How to use](#section-1) 11 | - [Custome Container](#sub-topic-1.1) 12 | - [Supported Data](#sub-topic-1.2) 13 | 3. [Storing Custome Data](#section-2) 14 | - [Example 1 Enums](#sub-topic-2.1) 15 | - [Example 2 Custom Array type](#sub-topic-2.2) 16 | 4. [RemovingStoredObjects](#section-3) 17 | 5. [Author](#conclusion) 18 | 19 | ## Introduction 20 | This package is crafted for effortless integration and streamlined access to user defaults plus it supports the new privacy rules from WWDC23. Adding it to your project is straightforward: simply include the package link in the main app package like this:" 21 | 22 | Screenshot 2024-03-15 at 3 28 47 AM 23 | 24 | Alternatively, navigate to the top section labeled 'Files' and click on 'Add Package Dependency': 25 | 26 | Screenshot 2024-03-15 at 3 33 08 AM 27 | 28 | Next, paste the repository link into the search field and click on 'Add Package': 29 | 30 | Screenshot 2024-03-15 at 3 34 52 AM 31 | 32 | ## How to use 33 | Utilizing this API is designed to be straightforward and as effortless as using the `@AppStorage` API But with more features. First this API is compile time safe and prevents any string typos. Simply declare your key in the `DefaultKeys` and then add the `@UserDefaults` to your `varible` as follows - that's all there is to it 34 | 35 | ```swift 36 | @UserDefaults(\.previewShown) var previewShown = false // false is the default value 37 | ``` 38 | 39 | ```swift 40 | extension DefaultKeys { 41 | var previewShown: String { .init("previewShown") } 42 | } 43 | ``` 44 | 45 | > [!NOTE] 46 | > You can also store optional values just like that: 47 | > ```swift 48 | > @UserDefaults(\.previewShown) var previewShown: Bool? 49 | > ``` 50 | 51 | ### Custome Container 52 | You can also store your userDefaults in a custome `container` like so: 53 | ```swift 54 | @UserDefaults(\.previewShown, .init(suiteName: "YourCustomeContainerName")) var previewShown = false 55 | ``` 56 | ### Supported Data 57 | SwiftUserDefaults supports all of the standard `NSUserDefaults` types, like `String`, `Int`, `Bool`, `Array` and much more. 58 | 59 | Here's a full table of built-in single value defaults: 60 | 61 | | Single value | Array | 62 | | ---------------- | -------------------- | 63 | | `String` | `[String]` | 64 | | `Int` | `[Int]` | 65 | | `Double` | `[Double]` | 66 | | `Bool` | `[Bool]` | 67 | | `Data` | `[Data]` | 68 | | `Date` | `[Date]` | 69 | | `URL` | `[URL]` | 70 | | `[String: Any]` | `[[String: Any]]` | 71 | 72 | But you can also support custome data types 🚀 73 | 74 | ## Storing Custome Data 75 | Storing custom data types is straightforward; you only need to ensure that the custom data type conforms to `DefaultsCustomDataType`, as demonstrated below: 76 | 77 | ```swift 78 | struct CustomeData: DefaultsCustomDataType { 79 | init() 80 | } 81 | @UserDefaults(\.customeData) var customeData = CustomeData() 82 | ``` 83 | 84 | `DefaultsCustomDataType` is a `public` `protocol` that conforms to the `Codable` protocol. It serves as a bridge, allowing the API to easily detect whether this data type needs to be encoded or not. 85 | 86 | ### Example 1 Enums 87 | Storing an `Enum` is straightforward; simply ensure that the `Enum` conforms to `DefaultsCustomDataType`, as shown below: 88 | 89 | ```swift 90 | enum CustomeData: DefaultsCustomDataType { 91 | case none 92 | } 93 | @UserDefaults(\.customeData) var customeData: CustomeData = .none 94 | ``` 95 | ### Example 2 Custom Array type 96 | Storing custom `Array` types is even simpler just ensure that the `Element` type of the `Array` conforms to `DefaultsCustomDataType`, as demonstrated below: 97 | 98 | ```swift 99 | struct CustomeData: DefaultsCustomDataType { 100 | init() 101 | } 102 | @UserDefaults(\.customeData) var customeData: [CustomeData] = [CustomeData()] 103 | ``` 104 | 105 | ## RemovingStoredObjects 106 | You can also remove the stored value for a specific key using the `DefaultKeys.removeObject(at keyPath: KeyPath, _ container: UserDefaults = .standard)`, as demonstrated below: 107 | 108 | ```swift 109 | @UserDefaults(\.testKey) var test = 3 110 | DefaultKeys.removeObject(\.testKey) 111 | // if you use a custome container provide it to the funcation using this syntax, 112 | // DefaultKeys.removeObject(at keyPath: KeyPath, _ container: UserDefaults = .standard) 113 | ``` 114 | 115 | > [!NOTE] 116 | > When you call `test` after removing the stored value, it will give the default value which is equal `3` in this case (which is not stored UserDefaults2 store). 117 | > if it was an `optional` the output will be `nil` in this case. 118 | 119 | if you want to delete all the values in the UserDefaults, you can use `DefaultKeys.removeAllUserDefaultsObjects(for container: UserDefaults = .standard)`: 120 | 121 | ```swift 122 | @UserDefaults(\.testKey) var test = 3 123 | DefaultKeys.removeAllUserDefaultsObjects() 124 | // if you use a custome container provide it to the funcation using this syntax, 125 | // DefaultKeys.removeAllUserDefaultsObjects(for container: UserDefaults = .standard) 126 | ``` 127 | 128 | And that's all there is to it! 🚀 Enjoy using this Swifty package. 129 | 130 | ## Author 131 | This pacakge was created by [Eng.Omar Elsayed](https://www.deveagency.com/) to help the iOS comuntity and make there life easir. To contact me email me at eng.omar.elsayed@hotmail.com 132 | 133 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Currently our package support security and access control for the code. 6 | 7 | | Version | Supported | 8 | | ------- | ------------------ | 9 | | 1.0.0 | :white_check_mark: | 10 | 11 | ## Reporting a Vulnerability 12 | 13 | if you want to report a Vulnerability please send email to eng.omar.elsayed@hotmail.com 14 | 15 | I will answer your consern as soon as possible, thanks for using my Pacakge. 16 | -------------------------------------------------------------------------------- /Sources/PrivacyInfo.xcprivacy: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NSPrivacyAccessedAPITypes 6 | 7 | 8 | NSPrivacyAccessedAPITypeReasons 9 | 10 | CA92.1 11 | 12 | NSPrivacyAccessedAPIType 13 | NSPrivacyAccessedAPICategoryUserDefaults 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Sources/UserDefaults/DefaultKeys.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | /// This is the place where all the keys will be stored. To add a new key, just make an extension and declare a new static String value 23 | @frozen 24 | public struct DefaultKeys { 25 | /// This is used to access the keys using the static subscript. 26 | private static let current = DefaultKeys() 27 | 28 | /// This subscript is used to access the stored keys 29 | public static subscript(_ key: KeyPath) -> String { 30 | return current[keyPath: key] 31 | } 32 | } 33 | 34 | //MARK: - Removing Stored Objects 35 | extension DefaultKeys { 36 | /// Clears all the objects stored in the specified container. By default it uses the ``.standard`` container. 37 | /// 38 | /// When you call the variable after removing it, you will get the default value you provided or nil if it was optional. 39 | public static func removeAllUserDefaultsObjects(for container: UserDefaults = .standard) { 40 | if let domainName = Bundle.main.bundleIdentifier { 41 | container.removePersistentDomain(forName: domainName) 42 | container.synchronize() 43 | } 44 | } 45 | 46 | /// Removes the Value at the specified keyPath. 47 | /// 48 | /// When you call the variable after removing it, you will get the default value you provided or nil if it was optional. 49 | public static func removeObject(at keyPath: KeyPath, _ container: UserDefaults = .standard) { 50 | container.removeObject(forKey: DefaultKeys[keyPath]) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Sources/UserDefaults/Protocols/AnyOptional.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | 23 | /// This protocol is made to make custom propertyWrapper work easily with optional values. Not indented to be used in any place outside the package. 24 | public protocol AnyOptional { 25 | var isNil: Bool { get } 26 | } 27 | 28 | extension Optional: AnyOptional { 29 | public var isNil: Bool { self == nil } 30 | } 31 | -------------------------------------------------------------------------------- /Sources/UserDefaults/Protocols/DefaultsCustomDataType.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | 23 | /// conform your data type to this protocol if you want to store custom data to the userDefaults. 24 | /// Note: All the child types should conform to Codable. 25 | public protocol DefaultsCustomDataType: Codable {} 26 | -------------------------------------------------------------------------------- /Sources/UserDefaults/UserDefaults.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | // 21 | import Foundation 22 | /// 23 | ///@UserDefault propertyWrapper used to store data in the userDefaults with easy. 24 | /// 25 | @frozen @propertyWrapper 26 | public struct UserDefault { 27 | private let key: String 28 | private let defaultValue: Value 29 | private let container: UserDefaults 30 | 31 | public var wrappedValue: Value { 32 | get { 33 | return getObject(forKey: key) 34 | } 35 | set { 36 | set(newValue) 37 | } 38 | } 39 | 40 | public init(wrappedValue: Value, _ keyPath: KeyPath, container: UserDefaults = .standard) { 41 | self.key = DefaultKeys[keyPath] 42 | self.defaultValue = wrappedValue 43 | self.container = container 44 | } 45 | 46 | @available(*, deprecated, message: "Please use init(wrappedValue: Value, _ keyPath: KeyPath, container: UserDefaults = .standard) instead for reference visit link: https://github.com/EngOmarElsayed/SwiftUserDefaults") 47 | public init(wrappedValue: Value, _ key: String, container: UserDefaults = .standard) { 48 | self.key = key 49 | self.defaultValue = wrappedValue 50 | self.container = container 51 | } 52 | 53 | } 54 | 55 | extension UserDefault where Value: ExpressibleByNilLiteral { 56 | public init(_ keyPath: KeyPath, _ container: UserDefaults = .standard) { 57 | self.init(wrappedValue: nil, keyPath, container: container) 58 | } 59 | 60 | @available(*, deprecated, message: "Please use init(wrappedValue: Value, _ keyPath: KeyPath, container: UserDefaults = .standard) instead for reference visit link: https://github.com/EngOmarElsayed/SwiftUserDefaults") 61 | public init(_ keyPath: String, _ container: UserDefaults = .standard) { 62 | self.init(wrappedValue: nil, keyPath, container: container) 63 | } 64 | } 65 | 66 | //MARK: - Set & Get of the UserDefault values 67 | extension UserDefault { 68 | private func getObject(forKey: String) -> Value { 69 | let data = container.object(forKey: key) 70 | 71 | if let data = data as? Data { 72 | return decode(data) ?? defaultValue 73 | } else { 74 | return data as? Value ?? defaultValue 75 | } 76 | } 77 | 78 | private func set(_ newValue: Value) { 79 | if let optional = newValue as? AnyOptional, optional.isNil { 80 | container.removeObject(forKey: key) 81 | 82 | } else if let newValue = newValue as? DefaultsCustomDataType { 83 | encode(newValue: newValue) 84 | 85 | } else { 86 | container.set(newValue, forKey: key) 87 | } 88 | } 89 | } 90 | 91 | //MARK: - Decoding & Encoding 92 | extension UserDefault { 93 | private func encode(newValue: DefaultsCustomDataType) { 94 | let encoder = JSONEncoder() 95 | let data = try? encoder.encode(newValue) 96 | container.set(data, forKey: key) 97 | } 98 | 99 | private func decode(_ data: Data) -> Value? { 100 | let decoder = JSONDecoder() 101 | let data = try? decoder.decode(Value.self, from: data) 102 | return data 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /Sources/UserDefaults/extension/ArrayExtension.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | 23 | // This extension was made to make the array conform to `DefaultsCustomDataType` only if the element conforms to the `DefaultsCustomDataType` 24 | extension Array: DefaultsCustomDataType where Element: DefaultsCustomDataType {} 25 | -------------------------------------------------------------------------------- /Tests/UserDefaultsTests/UserDefaultsTests.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import XCTest 22 | import UserDefaults 23 | 24 | internal final class UserDefaultsTests: XCTestCase { 25 | 26 | override func setUp() { 27 | super.setUp() 28 | deleteArtifactsFromUserDefaults(for: \.testKey) 29 | } 30 | 31 | override func tearDown() { 32 | super.tearDown() 33 | deleteArtifactsFromUserDefaults(for: \.testKey) 34 | } 35 | 36 | func test_UserDefaultWrapper_retrievingAfterInitializingValue() { 37 | let expectedResult = 9 38 | @UserDefault(\.testKey) var testValue = expectedResult 39 | 40 | XCTAssertEqual(testValue, expectedResult, "Expected to have the same value") 41 | } 42 | 43 | func test_UserDefaultWrapper_retrievingAfterOverRidingDefaultValue() { 44 | let expectedResult = 9 45 | @UserDefault(\.testKey) var testValue = 10 46 | 47 | testValue = expectedResult 48 | 49 | XCTAssertEqual(testValue, expectedResult, "Expected to have the same value") 50 | } 51 | 52 | func test_UserDefaultWrapper_retrievingAfterInitializingNilValue() { 53 | @UserDefault(\.testKey) var testValue: Int? 54 | 55 | XCTAssertNil(testValue, "Expected to be nil") 56 | } 57 | 58 | func test_UserDefaultWrapper_retrievingAfterOverRidingNilValue() { 59 | let expectedResult = 9 60 | @UserDefault(\.testKey) var testValue: Int? 61 | 62 | testValue = expectedResult 63 | 64 | XCTAssertEqual(testValue, expectedResult, "Expected to have the same value, got nil insted") 65 | } 66 | 67 | func test_UserDefaultWrapper_retrievingCustomDataTypeAfterInitializingValue() { 68 | let expectedResult = TestCustomType(id: 2) 69 | @UserDefault(\.testKey) var testValue = TestCustomType(id: 5) 70 | 71 | testValue = expectedResult 72 | 73 | XCTAssertEqual(testValue.id, expectedResult.id, "Expected to have the same value got \(testValue.id)") 74 | } 75 | 76 | func test_UserDefaultWrapper_retrievingDataTypeAfterInitializingValue() { 77 | let expectedResult = Data() 78 | @UserDefault(\.testKey) var testValue = Data() 79 | 80 | testValue = expectedResult 81 | 82 | XCTAssertEqual(testValue, expectedResult, "Expected to have the same value got \(testValue)") 83 | } 84 | 85 | func test_UserDefaultWrapper_removeAllUserDefaultsObjects_givesTheDefault() { 86 | let expectedResult = "2" 87 | @UserDefault(\.testKey) var testValue: String = "2" 88 | 89 | testValue = "5" 90 | DefaultKeys.removeAllUserDefaultsObjects() 91 | 92 | XCTAssertEqual(testValue, expectedResult, "Expected to have the same value got \(testValue)") 93 | } 94 | 95 | func test_UserDefaultWrapper_removeObjectFromUserDefaults_givesTheDefault() { 96 | let expectedResult = "2" 97 | @UserDefault(\.testKey) var testValue: String = "2" 98 | 99 | testValue = "5" 100 | DefaultKeys.removeObject(at: \.testKey) 101 | 102 | XCTAssertEqual(testValue, expectedResult, "Expected to have the same value got \(testValue)") 103 | } 104 | 105 | private func deleteArtifactsFromUserDefaults(for key: KeyPath) { 106 | UserDefaults.standard.removeObject(forKey: DefaultKeys[key]) 107 | } 108 | 109 | private struct TestCustomType: DefaultsCustomDataType { 110 | let id: Int 111 | } 112 | 113 | } 114 | 115 | fileprivate extension DefaultKeys { 116 | var testKey: String { 117 | .init("testKey") 118 | } 119 | } 120 | --------------------------------------------------------------------------------