Reflection of enum in Swift [duplicate] - swift

This question already has answers here:
Swift: Convert enum value to String?
(19 answers)
Closed 7 years ago.
Say I have an enum like this:
enum Direction {
case Left
case Right
}
Is there a way to derive a string description of the enum automatically without defining it myself? Something like this:
let direction: Direction = .Left
let description: String = direction.description // should be "Left"
I tried reflect( direction) and the properties on MirrorType but that didn't work.

Not currently. You'll need to implement a description function manually for this. Swift has very limited reflection.

I think the closest you can do is either implement description yourself or make the enum a string:
enum Direction: String {
case Left = "Left"
case Right = "Right"
}
You can then get the value via direction.rawValue. Obviously, not as great as what you are looking for though and it requires duplicating the enum value, which is dumb.
You can then use the raw value to implement the description if you want (allowing you to use direction.description:
var description: String {
return self.rawValue
}

Related

How to store enum states in CoreData in Swift? [duplicate]

This question already has answers here:
Swift: Storing states in CoreData with enums
(3 answers)
Closed 2 years ago.
I searched a lot and find general answer like "We generally store enumerations as strings or as integers into database"
But what if I have an enum like this? How can I store this to Core Data?
enum UserItemType {
case spring
case summer
case fall
case winter
}
Give the enum UserItemType a rawValue and store the rawValue in into database. RawValue can be Int or String as you wish. Here is how:
enum UserItemType: Int {
To convert back to enum from rawValue, here's the code:
let userItemType = UserItemType(rawValue: valueFromDatabase)

How to create a datatype with limited set of possibilities to switch on its value?

I would like to pass a value to a function that lets me pick which value to set from a set list. An example of using this would be a function that needs to behave differently based on the "mode" that the page is in like creating a new post or editing an existing one. I currently am doing this by passing a string parameter into the function with "new" or "edit" in the string. I thought the right way to do this was to create an enum so that the value that is passed is that enum type and I don't have to worry about a typo breaking the app.
I thought I just had to declare an enum with my options as cases and then could just use it like you would a customer data type. That didn't work for me and either I am making a silly mistake or this wasn't how this is supposed to be used.
// -------------
// Current Code
func filterBySwitch(filterOption: String){
print("You asked me to filter by \(filterOption)")
}
filterBySwitch(filterOption: "userOwns")
// -------------
// I though this is how I would pass the argument when only 3 available options
enum filterType {
case userHeart
case userOwns
case userSeen
}
func filterBySwitch(filterOption: filterType){
print("You asked me to filter by \(filterType)")
}
filterBySwitch(filterOption: .userOwns)
You may want to do something like this:
enum FilterType {
case userHeart
case userOwns
case userSeen
}
func filterBySwitch(filterOption: FilterType){
print("You asked me to filter by \(filterOption)") //<-
}
filterBySwitch(filterOption: .userOwns)
In Swift, you use capitalized identifier for type, such convention will help you find such mistakes easier.

Why can't I put an enum case in single quotes which is of type Int? [duplicate]

This question already has an answer here:
Use reserved keyword a enum case
(1 answer)
Closed 4 years ago.
I'm following a tutorial and it says to type in the code below:
import UIKit
enum Theme: Int {
//1
case `default`, dark, graphical
//2
private enum Keys {
static let selectedTheme = "SelectedTheme"
}
//3
static var current: Theme {
let storedTheme = UserDefaults.standard.integer(forKey: Keys.selectedTheme)
return Theme(rawValue: storedTheme) ?? .default
}
}
This seemed to be fine and well however I began researching online what exactly an enum in Swift is. One piece of information I found online said that I could break out each case on its own line as shown below:
import UIKit
//We're creating an enum!
enum Theme: Int {
//1
case 'default'
case dark
case graphical
//2
private enum Keys {
static let selectedTheme = "SelectedTheme"
}
}
However I get a compile time error that says 'Expected identifier in enum 'case' declaration and I'm not sure what this means. Can anyone please explain why can't I break out each case on its own line in this example?
Thanks to the fine comment above for help. The reason is because the word "default" is a keyword that is reserved in the Swift language therefore in order to use it within my own program in a different way than suggested by the Swift language then I will need to place with word within backticks. See this SO question for reference: Use reserved keyword a enum case

Can I make a Swift data type infix operator?

So, I want to make an operator ('or') which will allow me to declare a variable like this:
var someNum: Int or Double
This bring an example. I want to actually use it on some custom made data types. But is it possible to make an operator for variable declarations that will allow for said variable to be one of two types depending on what its being assigned? I know what data types are possible of being entered, but unfortunately I would currently either assign it a type of 'Any' with a bunch of failsafe code implemented or change the original data types created. So I was just wondering if this is possible or might even exist.
I used this article as a reference, but from what I read I'm not sure if I can or how I would implement it for my needs.
Custom Operators in Swift
Thanks for any and all the help in advance.
You can't do this in the way you're asking. It's not possible syntactically to use a operator in a declaration like that.
What you can do is use an enum to distinguish the kinds:
enum NumericInput {
case integral(Int)
case fractional(Double)
}
and take that as the type of your variable:
var value: NumericInput
Then you say
value = .integral(someInteger)
You could do this with generics:
struct MyStruct<T>
{
var someNum: T
}
You can then explicitly state the dataType you wish to use by specifying the type on creation: let a = MyStruct<Int>(someNum: 4).
One thing Swift does that makes this all absolutely beautiful is derive the data type from the constructor, so you can also just do this:
let intStruct = MyStruct(someNum: 4)
let floatStruct = MyStruct(someNum: 5.0)
You can just declare the value with type Any.
For example,
var myVar: Any = shouldAssignDouble ? Double(20) : Float(20)
Later when you want to know if the actual type is a Float or Double, you can check it with
myVar is Double //returns true

ios how can implement a switchs/case with string? [duplicate]

This question already has answers here:
Using an NSString in a switch statement
(9 answers)
Closed 9 years ago.
I want to implement a switchs/case where I can use a string to evaluate the switch case.
switch (tmp) {
case one:
NSLog(#"the string value of tmp is one");
break;
any of you knows how can I implement something like this?
I really appreciate your help
You can not use string in switch case statement, you can use only int or char data type.
But as i think your question is to make switch case more easy to understandable or readable.
So you can make enum for that, like:
typedef enum {
zero,//by default the value starts from zero.
one,
two
} NumCount;
At the point you have use it.
NumCount tmp = one;
switch (tmp) {
case one:
NSLog(#"the string value of tmp is one");
break;
}
I think you understand what i want to say. If you have any doubt please ask from me.