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 {...}.
Related
Well...here is the code
func howMany() -> Int {
return 10
}
func Call() -> Void {
guard case let output = howMany(), output > 5 else { return }
}
Call()
I do not really understand how the guard case works. This looks pretty much like a pattern matching condition where we compare whether the result of howMany() is equal to output, if it is, assign the value to output and then compare it to the literal value 5. However, when I deleted the line of output > 5, the compiler said, "the guard condition is always true, body is unreachable."
According to the pattern, if we translate it into a switch statement, it looks pretty much like this
switch howMany() {
case let output where output > 5:
break;
}
The question is if it could be directly translated into the switch statement, then there should not be a warning of "the guard condition is always true, body is unreachable" when we delete the where condition.
I hope somebody could shed some light on this.
Consider:
func foo() {
guard case let output = howMany(), output > 5 else {
print("less than or equal to 5")
return
}
print("\(output) is greater than 5")
}
That is roughly equivalent to:
func bar() {
switch howMany() {
case let output where output > 5:
print("\(output) is greater than 5")
default:
print("less than or equal to 5")
return
}
}
If you remove that > 5 criteria:
func foo() {
guard case let output = howMany() else {
print("less than or equal to 5")
return
}
print("\(output) is greater than 5")
}
You get your warning:
'guard' condition is always true, body is unreachable
That warning is correct, because the body is unreachable.
And if you do the equivalent in the switch example:
func bar() {
switch howMany() {
case let output:
print("\(output) is greater than 5")
default:
print("less than or equal to 5")
return
}
}
If you do that, you will receive an analogous warning:
default will never be executed
And, again, it makes sense, because default will not be reached.
Now, consider your example switch with no default clause:
func bar() {
switch howMany() {
case let output:
print("output:", output)
}
}
You don't receive a warning here only because there is no default clause (the analog of the "body" of the guard statement).
I realise this has been asked before, but the answer here (to declare the variable outside the block) doesn't seem to work.
link description
var filter: String
func Usage() {
print("Usage: <filter> <input> [output]")
print("System filter paths do not need to be specified.")
return
}
let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)
switch arguments.count {
case 1:
Usage()
case 2:
Usage()
case 3:
filter = arguments[1]
default:
filter = arguments[1]
print (filter)
}
print (filter)
I get "value" in Xcode's playground for the first print, but the second gives "\n" or "value not initialized".
What am I doing wrong?
Your code won´t compile first of all, you do get the error error: variable 'filter' used before being initialized
So declare filter as follow:
var filter = String() or var filter = ""
Secondly since you´re not adding all of your code I tried the following:
var filter = String()
let x = 0
switch x {
case 1:
print("1")
default:
filter = "value"
print(filter)
}
print(filter)
This prints out:
value
value
If you need further help update your question with more information.
Update:
Just tried your updated code:
var filter = String()
let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)
switch arguments.count {
case 1:
break
case 2:
break
case 3:
filter = arguments[1]
default:
filter = arguments[1]
print (filter)
}
print (filter)
And this prints out:
4
value
value
Which is exactly what it should print out. Remember the initialization of filter.
Update 2:
This is what you´re trying to do, your other result was always return 4 because that´s the count of arguments. Try the below code instead.
var filter = String()
func Usage() {
print("Usage: <filter> <input> [output]")
print("System filter paths do not need to be specified.")
return
}
let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)
for i in 0..<arguments.count {
switch i {
case 0:
Usage()
case 1:
Usage()
case 2:
Usage()
case 3:
filter = arguments[1]
default:
filter = arguments[1]
print (filter)
}
}
print (filter)
This prints out:
4
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
value
Your code seems to be an entry point for a command line interface.
This is an alternative approach without declaring a global variable and without a switch.
Usage is printed if the number of arguments is less than 3 otherwise the first two arguments after the name of CLI (at index 0) are assigned to two variables.
let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)
if arguments.count < 3 {
Usage()
exit(EXIT_FAILURE)
}
let filter = arguments[1]
let secondArgument = arguments[2]
print (filter, secondArgument)
Then you could switch over the filter
switch filter {
case "value": doThis(with: secondArgument)
case "someOtherFilter": doThat(with: secondArgument)
default: doNothing()
}
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 working on integrating an IDTech swiper into my app and I've gotten pretty far along, added the library, registered notifications, unregistered them, and now I'm working on a function that connects the reader. I can't seem to figure out what I'm doing wrong here when I'm attempting to switch cases based on a return value.. could someone please help me?
func displayUmRet(operation: String, returnValue: UmRet) {
var string = ""
do {
switch returnValue {
case UMRET_SUCCESS: string = ""
case UMRET_NO_READER: string="No reader attached"
case UMRET_SDK_BUSY: string="Communication with reader in progress"
case UMRET_MONO_AUDIO: string="Mono audio enabled"
case UMRET_ALREADY_CONNECTED: string="Already connected"
case UMRET_LOW_VOLUME: string="Low volume"
case UMRET_NOT_CONNECTED: string="Not connected"
case UMRET_NOT_APPLICABLE: string="Not applicable to reader type"
case UMRET_INVALID_ARG: string="Invalid argument"
case UMRET_UF_INVALID_STR: string="Invalid firmware update string"
case UMRET_UF_NO_FILE: string="Firmware file not found"
case UMRET_UF_INVALID_FILE: string="Invalid firmware file"
default: string="<unknown code>"
}
} while (0)
// var retStatus = UMRET_SUCCESS==ret
//self.textResponse.text = "\(operation), \(retStatus), \(string)"
self.hexResponse.text = "";
}
You need to put a . before your cases:
enum UmRet {
case UMRET_SUCCESS, UMRET_FAILURE
}
var string = " "
let returnValue = UmRet.UMRET_SUCCESS
switch returnValue {
case .UMRET_SUCCESS: string = "y"
case .UMRET_FAILURE: string = "n"
}
Also, 0 isn't the same as false in Swift, so:
do {
...
} while (0)
Shouldn't work either.
And you don't need semicolons at the end of a line, so this:
self.hexResponse.text = "";
can be this:
self.hexResponse.text = ""
And finally, if your switch statement has every case for every case in your enum, you don't need a default case. (that's why mine didn't have one in the example)
By the way, ~= is just the operator for the pattern-matching function, which is what Swift does in a switch statement. It works kind of like the == function, for instance, Int ~= Int is the same as Int == Int. But it's a bit more versatile: for instance Range ~= Int, eg 0...3 ~= 2 returns whether or not the Int is in the range. (So true in this case) For enums, it matches cases to cases. In my example, it'll match UMRET_SUCCESS, and string will be set to y.