I want to know the major use cases with example will be great.
Where to use enum -> common example suppose you want to a show week days name “MONDAY – SUNDAY” in a dropdown menu at that time you know week days data is constant and will never change.
example:
enum day {
sunday,
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
}
void main() {
// assume you app user will select from Menu Item day
var selectedEnumDay = day.friday;
// Switch-case
switch(selectedEnumDay) {
case day.sunday: print("You selected sunday");
break;
case day.monday: print("You selected monday");
break;
case day.tuesday: print("You selected tuesday");
break;
case day.wednesday: print("You selected wednesday");
break;
case day.thursday: print("You selected thursday");
break;
case day.friday: print("You selected friday");
break;
case day.saturday: print("You selected saturday");
break;
}
}
Enum are a special type of class that allow creating a set of constant values associated with a particular type. [ 1 ]
Enums are great for representing a discrete set of states. [ 2 ]
one of simple example using enum is :
enum RequestState {success, error, notAsked, loading }
...
RequestState apiState = RequestState.notAsked;
Widget buildContaier() {
switch(apiState){
case apiState.loading:
return CircularProgressIndicator();
case apiState.success:
return ListView();
case apiState.error:
return Text("error fetch api");
default:
return Container();
}
Related
As you see I am new at coding.
I am trying to print the correct week day on switch case.
But i can't.
What is wrong with my code?
var aNumber = Int.random(in: 0...10)
func dayOfTheWeek(day: Int) {
switch dayOfTheWeek {
case ..<2:
print ("Monday")
case ..<3:
print ("Tuesday")
case ..<4:
print ("Wednesday")
case ..<5:
print ("Thursday")
case ..<6:
print ("Friday")
case ..<7:
print ("Saturday")
case ..<8:
print ("Sunday")
default:
print("Error")
}
print(aNumber)
}
dayOfTheWeek(day: aNumber)
You need to switch on the parameter day (instead of the function name), and you don't need to match ranges like ..<2 only single numbers:
switch day {
case 2:
print ("Monday")
case 3:
print ("Tuesday")
// and so on...
dayOfTheWeek is the function, while day is the Int.
Therefore, you have to switch through the Integer.
Try switch day {...}.
This question already has answers here:
Swift switch pattern matching with arrays
(3 answers)
Closed 6 years ago.
I want to put my array of values as a case for my switch statement
I have an array of values say
let intValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 .... 100]
and I want to use a switch statement to be used as a comparison tool like so.
let inputValue = 30 // or some other int value
switch inputValue {
case 101:
// do something lol
/* =============================== */
case intValues: //
// do something more:
/* =============================== */
case 13131:
// do another thing
default:
// do default
}
I know I can do this easily by either doing this case 1, 2, 3, 4, 5, and so on or by using an if statement like so:
if intValues.contains(inputValue) {
// do something more:
} else if inputValue == 101 {
// do something lol
} else if inputValue == 13131 {
// do another thing
} else {
// do default
}
or by doing somethig like
if intValues.contains(inputValue) {
// do something more:
} else {
switch inputValue {
case 101:
// do something lol
case 13131:
// do another thing
default:
// do default
}
}
and vice versa
But is it possible though? to do it with just a switch statement?
You can use case let with where for that.
let intValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
let inputValue = 30 // or some other int value
switch inputValue {
case let x where intValues.contains(x):
// do something more:
case 101:
// do something lol
case 13131:
// do another thing
default:
// do default
}
You can do this with range operator.
let inputValue = 30
switch value {
case 1...100:
print("between hundred")
case 101:
print("it's 101")
default:
print("outer value")
}
You should just use a countable closed range in your switch cases:
let inputValue = 30
switch inputValue {
case 1...10:
print(1...10)
case 11...20:
print(11...20)
case 21...100:
print(21...100) // "21...100\n"
default:
print("default")
}
this is my code:
enum SymptomPeriod {
case Day
case Night
}
enum SymptomType {
case Breathing(SymptomPeriod)
case Breathlessness(SymptomPeriod)
case Opression(SymptomPeriod)
case Cough(SymptomPeriod)
case ActivityLimited()
case SecureTreatment()
}
struct Symptom {
let type: SymptomType
let date: NSDate
}
And i have an array of symptoms.
let symptomList: [Symptom] = ...
My need is to filter the list of symptoms with the SymptomPerion criteria, i trying to do like this:
let daySymtoms = symptomList.filter { (symptom) -> Bool in
return symptom.type = ???
}
My problem is in the filter function.
(My goal is to use a filter function and not a loop)
A few suggestions
Use your struct as namespace
Instead of repeating the word Symptom (e.g. SymptomPeriod, SymptomType) you should put your enums into you Symptom struct
Rename SymptomType as Kind
Once you moved SymptomType into Symptom you can drop the Symptom part of the name. However using Type as name will create a conflict so you should rename it Kind.
Add the period computed property to Kind
This will make the filtering much easier
Here's the code
struct Symptom {
enum Period {
case Day
case Night
}
enum Kind {
case Breathing(Period)
case Breathlessness(Period)
case Opression(Period)
case Cough(Period)
case ActivityLimited()
case SecureTreatment()
var period: Period? {
switch self {
case Breathing(let period): return period
case Breathlessness(let period): return period
case Opression(let period): return period
case Cough(let period): return period
default: return nil
}
}
}
let kind: Kind
let date: NSDate
}
The solution
Now the filtering has become very easy
let symptoms: [Symptom] = ...
let filtered = symptoms.filter { $0.kind.period == .Day }
This is how i am doing it:
let daySymtoms = symtoms.filter { (symptom) -> Bool in
switch symptom.type {
case .Breathing(.Day), .Breathlessness(.Day), .Opression(.Day), .Cough(.Day):
return true
default:
return false
}
}
Let me know if you have more simple way to do it.
I'm new to Swift iOS.. I'm trying to use enum type as input parameter to a function.. here is the
sample enum type:
public enum CFScreen {
public enum CFScreen_Newsfeed: Int {
case Newsfeed_01 = 2100
case Newsfeed_02 = 2101
case Newsfeed_03 = 2102
case Newsfeed_04 = 2103
case Newsfeed_05 = 2104
case Newsfeed_06 = 2105
case Newsfeed_07 = 2106
case Newsfeed_08 = 2107
}
public enum CFScreen_Groups: Int {
case Create = 2200
case GoBack = 2201
}
}
sample function using enum type as input parameter
func showCFScreenForEnumType(cFooter: CFScreen.CFScreen_Groups) {
//Group Related
switch cFooter {
case .Create:
print("Show Create Group")
break
case .GoBack:
print("Show Go Back Screen")
break
}
}
func showCFScreenForEnumType(cFooter: CFScreen.CFScreen_Newsfeed) {
//Group Related
switch cFooter {
case .Newsfeed_01:
print("Show News 01")
break
case .Newsfeed_02:
print("Show News 02")
break
case .Newsfeed_03:
print("Show News 03")
break
case .Newsfeed_04:
print("Show News 04")
break
case .Newsfeed_05:
print("Show News 05")
break
case .Newsfeed_06:
print("Show News 06")
break
case .Newsfeed_07:
print("Show News 07")
break
case .Newsfeed_08:
print("Show News 08")
break
}
}
Calling this functions as follows
let selCFScreenG = CFScreen.CFScreen_Groups.Create
showCFScreenForEnumType(selCFScreenG)
let selCFScreenNF = CFScreen.CFScreen_Newsfeed.Newsfeed_01
showCFScreenForEnumType(selCFScreenNF)
Taken Reference from link: http://www.codingexplorer.com/enumerations-swift/
My question is how i can write a function that will accepting enum types generically so that i can merge these below two functions into one
func showCFScreenForEnumType(cFooter: CFScreen.CFScreen_Groups)
func showCFScreenForEnumType(cFooter: CFScreen.CFScreen_Newsfeed)
You could create a generic type constraint to some protocol, say MyCFScreenEnums, to which only the two enums in CFScreen conforms, and within the function that makes use of this (type constrained) generic, perform attempted type conversion to one of the two enums CFScreen.CFScreen_Newsfeed/CFScreen.CFScreen_Newsfeed. Since only these two conform to MyCFScreenEnums, one of these type conversions is guaranteed to be successful due to the type constraint of the generic (say T) to MyCFScreenEnums.
protocol MyCFScreenEnums { }
extension CFScreen.CFScreen_Newsfeed : MyCFScreenEnums {}
extension CFScreen.CFScreen_Groups : MyCFScreenEnums {}
func showCFScreenForEnumType<T: MyCFScreenEnums>(cFooter: T) {
if let newsfeed = cFooter as? CFScreen.CFScreen_Newsfeed {
switch newsfeed {
case .Newsfeed_01: print("Show News 01")
case .Newsfeed_02: print("Show News 02")
case .Newsfeed_03: print("Show News 03")
case .Newsfeed_04: print("Show News 04")
case .Newsfeed_05: print("Show News 05")
case .Newsfeed_06: print("Show News 06")
case .Newsfeed_07: print("Show News 07")
case .Newsfeed_08: print("Show News 08")
}
}
else if let groups = cFooter as? CFScreen.CFScreen_Groups {
switch groups {
case .Create: print("Show Create Group")
case .GoBack: print("Show Go Back Screen")
}
}
}
/* Example usage */
let foo = CFScreen.CFScreen_Newsfeed.Newsfeed_03
let bar = CFScreen.CFScreen_Groups.Create
showCFScreenForEnumType(foo) // "Show News 03"
showCFScreenForEnumType(bar) // "Show Create Group"
I'm working on an open source project while learning swift at the same time, the github repository is available at https://github.com/istx25/schedules. I'm trying to add an identifier to the case that will run a function everytime the button is pressed in a UIActionSheet. The code for the action sheet is as follows:
#IBAction func rightButton(sender : AnyObject) {
var sheet: UIActionSheet = UIActionSheet()
let title: String = "Please choose a block rotation"
sheet.title = title
sheet.delegate = self
sheet.addButtonWithTitle("Cancel")
sheet.addButtonWithTitle("Day Four")
sheet.addButtonWithTitle("Day Three")
sheet.addButtonWithTitle("Day Two")
sheet.addButtonWithTitle("Day One")
sheet.cancelButtonIndex = 0
sheet.showInView(self.view)
}
and I've started the switch to defer which button is which as:
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
case 0:
print("Go Back")
case 1:
print("Day Four")
// Day Four Function
case 2:
print("Day Three")
// Day Three Function
case 3:
print("Day Two")
// Day Two Function
case 4:
print("Day One")
// Day One Function
default:
print("Something's broken")
}
}
I'm wanting each case to be pushed to it's own func method and I'm not sure exactly how I would approach this, so please if anybody could help that would be great. If this question is hard to understand please tell me; so I can get better at asking for help on Stackoverflow! Thanks in advance.
If you're targeting iOS 8 then you shouldn't be using UIActionSheets as they are deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet and add actions to it with the addAction() method.
I'm not familiar with Swift (yet), but the usual setup is not with switch/case. Instead each button is associated with an action. That might be a callback. Here, UIControl.sendAction and related code looks like the place to start.
You could create a separate func, and pass in buttonIndex. There you could either do if's or the same switch.
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
case 0:
print("Go Back")
theFuction(buttonIndex)
case 1:
print("Day Four")
// Day Four Function
theFuction(buttonIndex)
case 2:
print("Day Three")
// Day Three Function
theFuction(buttonIndex)
case 3:
print("Day Two")
// Day Two Function
theFuction(buttonIndex)
case 4:
print("Day One")
// Day One Function
theFuction(buttonIndex)
default:
print("Something's broken")
}
}
func theFuction (btnIndex: Int) {
if btnIndex == 0 {
} else if btnIndex == 1 {
} else if btnIndex == 2 {
} else if btnIndex == 3 {
} else if btnIndex == 4 {
}
}