Swift userdefaults enum

Swift 5 Xcode 11 iOS From time to time, however, you need to perform a task that is less trivial. How do you clear the user's defaults database? The UserDefaults class doesn't offer this functionality. What options do you have to reset the user's defaults database in Swift? The documentation of the UserDefaults class lists a method in the Legacy section that seems to do the trick.

The method is named resetStandardUserDefaults. Don't get your hopes up, though. The description of the method says "This method has no effect and shouldn't be used. Create a playground, add the following code snippet, and run the contents of the playground. The output in the console confirms that the resetStandardUserDefaults method has no effect.

It doesn't clear or reset the user's defaults database. To remove a key-value pair from the user's defaults database, you need to invoke removeObject forKey: on the UserDefaults instance. Let's update the previous example. The output in the console confirms that the removeObject forKey: method works as advertised. The removeObject forKey: method also works fine if you need to remove multiple key-value pairs. For that to work, you need to carefully keep track of the data you store in the user's defaults database.

There are several solutions to accomplish this. Let's take a look at one of them. We start by defining an extension for the UserDefaults class. In the extension, we create a enum with name Keys and String as the raw value. The Keys enum manages the keys used to store data in the user's defaults database. We conform the Keys enum to the CaseIterable protocol. Why is this necessary? If we conform the Keys enum to the CaseIterable protocol, a computed property with name allCases automatically becomes available.

IsMultipleOf and Future Enums and Swift 5

This computed property returns an array that includes every case the Keys enum defines. This comes in useful in a few moments. With the Keys enum in place, we can implement an instance method with name reset. The implementation requires a single line of code. We ask the Keys enum for the array of cases using the allCases computed property.

We invoke the removeObject forKey: method on the UserDefaults instance, passing in the raw value of the case. That's it.GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together. If nothing happens, download GitHub Desktop and try again. If nothing happens, download Xcode and try again.

If nothing happens, download the GitHub extension for Visual Studio and try again. Previous versions' documentation: Version 4. Just create a DefaultsKey object, put the type of the value you want to store in angle brackets, the key name in parentheses, and you're good to go. If you want to have a non-optional value, just provide a defaultValue in the key look at the example above.

The compiler won't let you set a wrong value type, and fetching conveniently returns String. For extra convenience, define your keys by extending magic DefaultsKeys class and adding static properties:. SwiftyUserDefaults supports all of the standard NSUserDefaults types, like strings, numbers, booleans, arrays and dictionaries. Since version 4, SwiftyUserDefaults support Codable!

Just conform to DefaultsSerializable in your type:. No implementation needed! By doing this you will get an option to specify an optional DefaultsKey :. NSCoding was supported before version 4, but in this version we take the support on another level. No need for custom subscripts anymore! Support your custom NSCoding type the same way as with Codable support:. No implementation needed as well!

And the last but not least, RawRepresentable support! Again, the same situation like with NSCoding and Codable :. Extending it to be SwiftyUserDefaults -friendly should be as easy as:. If you want to add your own custom type that we don't support yet, we've got you covered.

Unfortunately, if you find yourself in a situation where you need a custom bridge, you'll probably need to write your own:.To avoid naming collisions with other libraries and frameworks, an Objective-C class needs to have a unique name. Swift modules make the need for class prefixes obsolete. Even though modules are an important step forward, they're not as flexible as many developers would want them to be. Swift currently doesn't offer a solution to namespace types and constants within modules.

A common problem I run into when working with Swift is defining constants in such a way that they are easy to understand by anyone working on the project. In Objective-C, this would look something like this.

Every constant is prefixed with two or three letters to avoid naming collisions and the name of the constant describes its use in the project.

swift userdefaults enum

This works fine, but it isn't pretty or easy to read. But it's still better than using string literals throughout the project. Even though Swift doesn't support namespaces within modules, there are a few viable solutions to this problem. The first solution uses structs to create namespaces and it looks something like this.

We define a struct, APIand declare one or more static constant properties. I believe this solution was first coined by Jesse Squires.

It works great, it's easy to adopt, and the syntax to access the constants is intuitive and easy to read. There's one unwanted side effect.

The API struct can be instantiated. While this isn't a problem in itself, it may confuse other developers working on the project. You could declare the initializer of the API struct private, making it inaccessible to other parts of the project.

How to Clear or Reset User Defaults in Swift

Another solution was proposed by Joseph Lord in a discussion on Twitter and written about by Natasha Murashev. Instead of using structs, Joseph proposed to use enums without cases. An enum without cases cannot be instantiated, but it can act as a namespace.

This solution is almost identical to the one that uses a struct. The main difference is you cannot create an instance of the API enum without having an error thrown at you. Using enums or structs to create namespaces works very well for me. You don't need to put the constants of your project in a single enum or struct. Take a look at the following, more advanced, example. You have to admit that this look quite appealing, especially when compared to Objective-C.

We create an extension for the UserDefaults class and define a nested enum, Keys. This pattern may look a bit odd at first, but it works very well. Not only does it make working with constants easier, it's a simple pattern that's very easy to pick up.

Using Structs Even though Swift doesn't support namespaces within modules, there are a few viable solutions to this problem.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

I understand that a Swift enum isn't an NSObject, and that makes it difficult to save, but I'm unsure what the best way is to convert it to something storable. Using rawValue for the enum is one way of using types that can be stored in NSUserDefaults, define your enum to use a rawValue. Raw values can be strings, characters, or any of the integer or floating-point number types :.

You can also create an enum instance directly using the rawValue which could come from NSUserDefaults like:. Learn more.

swift userdefaults enum

Asked 5 years, 2 months ago. Active 9 months ago. Viewed 19k times. Active Oldest Votes. And for those looking for the read For anyone having issues with the rawValue initializer or property on your enum, make sure that your enum extends the type of your rawValue. For example, in OP's example, Environment extends String. I missed this the first time around. Since you have no control about what is stored in preferences, you should check that defaults. If the type you extend is literal-convertible from either String or Intyou don't even need to define explicit raw values for each case, since they can be automatically assigned consistently with the type you extend: a string containing the case name for String enums; a progressive number for IntFloat and Double enums.

Mobile number location tracker ethiopia

AlexSmith, you still should use. I was just saying that when you define your ConnectionType enum you don't need to explicitly assign an integer value to each case.Imagine you have an app and you want to implement auto login functionality for your app. Thus you create an UserDefaults wrapper to encapsulate the UserDefaults read and write logic.

This is how your UserDefaults wrapper usually looks like:. With Property Wrapper introduced in Swift 5. To define a property wrapper, you can use the keyword propertyWrapper. You can create a property wrapper named Printable as shown below:. As you can see from the code above, property wrapper is just like any other struct in Swift. However a wrappedValue is compulsory when defining a property wrapper.

The wrappedValue get and set block is where you can intercept and perform the operation you desire. In this example, a print statement is added to print out the value being get or set. If you try out above code in your Xcode Playground, you will see console output as shown below:.

After understanding how property wrapper works, we are now ready to start implementing our UserDefaults wrapper. Here we named our property wrapper Storage. It has 2 properties which is key and defaultValue. With the Storage property wrapper ready, we can start implementing the UserDefaults wrapper. It is pretty straightforward, we just need to create a username variable that is wrapped by the Storage property wrapper. Do note how you can initialise the Storage property wrapper with key and defaultValue.

swift userdefaults enum

With all that, the UserDefaults wrapper is finally ready to use. This is because our property wrapper currently only support String data type. In order to fix both errors, we will have to make our property wrapper generic. Furthermore, we will have to update the wrappedValue get block to use a generic way to read from UserDefaults.

With a generic property wrapper, our UserDefaults wrapper can now store a boolean value without any problem. But what if we need to store a custom object? Currently we will encounter an error if we try to store a custom object.

The concept here is simple, we will store the custom object as data in UserDefaults.Swift 4 Xcode 9 iOS If you're watching this, then I assume you're familiar with Swift extensions. A Swift extension allows you to add functionality to a type, a class, a struct, an enum, or a protocol.

But extensions are more powerful than that. In this episode, I'd like to show you four clever uses of Swift extensions. The Swift Programming Language mentions that extensions can be used to conform an existing type to a protocol.

While this isn't new or revolutionary, it can also help you keep your code organized. This example may look familiar. This is fine, but it results in a lengthy class implementation that can become difficult to navigate over time.

Subscribe to RSS

You can keep your code organized by creating an extension for each protocol the type conforms to. Navigating source files also becomes easier if you make it a habit to use the jump bar at the top of Xcode's source editor. I learned the next trick from Chris Eidhof. For this example, we first need to define a structure, Person. The structure defines two constant properties of type Stringfirst and last.

Swift generously creates an initializer for us, init first:last:which we can use to instantiate an instance of the Person structure. This isn't new. Unfortunately, the initializer is no longer available if we define a custom initializer in the struct's definition. Fortunately, we have an easy workaround to resolve this issue.

We create an extension for the Person struct in which we define the custom initializer. We can take the previous example one step further. A few years ago, Natasha Murashev outlined a technique that uses extensions to separate state from behavior. If we apply this technique to the previous example, we end up with something like this. The type definition only defines the stored properties.

An extension is created for the behavior of the type, that is, methods and computed properties. The result is a clear separation of state stored properties and behavior methods and computed properties. Code separation and organization is very easy to do using extensions.With a Raw Representable type, you can switch back and forth between a custom type and an associated Raw Value type without losing the value of the original Raw Representable type. Using the raw value of a conforming type streamlines interoperation with Objective-C and legacy APIs and simplifies conformance to other protocols, such as EquatableComparableand Hashable.

The Raw Representable protocol is seen mainly in two categories of types: enumerations with raw value types and option sets. For any enumeration with a string, integer, or floating-point raw type, the Swift compiler automatically adds Raw Representable conformance. You can also use literals to specify values for one or more cases.

Tamil divorced aunties mobile number in tirupur

For example, the Counter enumeration defined here has an Int raw value type and gives the first case a raw value of 1 :. You can create a Counter instance from an integer value between 1 and 5 by using the init? Option sets all conform to Raw Representable by inheritance using the Option Set protocol. For example, the Direction type defines an option set for the four directions you can move in a game.

Option set values have a one-to-one correspondence with their associated raw values. In the case of the Directions option set, an instance can contain zero, one, or more of the four defined directions.

This example declares a constant with three currently allowed moves. Option sets use bitwise operations on their associated raw values to implement their mathematical set operations. For example, the contains method on allowed Moves performs a bitwise AND operation to check whether the option set contains an element.

Four Clever Uses of Swift Extensions

These initializer overloads are available for any conforming type with a Raw Value that is a Decodable standard library type. These overloads are available for any conforming type with a Raw Value that is an Encodable standard library type. Protocol Raw Representable. A type that can be converted to and from an associated raw value. SDK Xcode 6. Framework Swift Standard Library.

Icas science paper d

Declaration protocol RawRepresentable. Topics Creating a Value. Raw Value Creates a new instance with the specified raw value. Accessing the Raw Value. Raw Value The corresponding value of the raw type.

Comparing Values. Decoding a Value.

Lagnachi mahiti

Encoding a Value. Instance Properties. Instance Methods. Relationships Inherited By. Option Set. Conforming Types. ABPerson Image Format.

ACError Code. ARFace Anchor. Blend Shape Location. Joint Name.

thoughts on “Swift userdefaults enum”

Leave a Reply

Your email address will not be published. Required fields are marked *