switch case in dart is not working properly - dart

I am trying to use switch case but it is behaving weirdly. For some inputs it is working and for some inputs it is not working. I checked the input values and found that they are good for the condition to be satisfied. Please help. I am new to flutter and dart.
I tried to achieve this with if-else if. Even that did not work for me.
List<String> lstNames = List<String>();
lstNames.addAll(["Dividends INR", "Payout Ratio % *", "Operating Cash Flow INR Mil", "Cap Spending INR Mil", "Free Cash Flow INR Mil"]);
for(String ItemHeading in lstNames){
switch (ItemHeading) {
case '' :
break;
case 'Dividends INR':
{/*Doing something.*/}
break;
case 'Payout Ratio % *':
{/*Doing something.*/}
break;
case 'Operating Cash Flow INR Mil':
{/*Doing something.*/}
break;
case 'Cap Spending INR Mil':
{/*Doing something.*/}
break;
case 'Free Cash Flow INR Mil':
{/*Doing something.*/}
break;
default:
break;
}
}
In the above code, based on the strings in lstNames I am trying to run the switch case. The string values contained by Elements in lstRows are {Dividends INR, Payout Ratio % *, Operating Cash Flow INR Mil, Cap Spending INR Mil, Free Cash Flow INR Mil}. The case for 'Payout Ratio % *' works. For the rest, it just skips/jumps to the next case and exits. Please help. Let me know if anymore information is required for debugging this.

EDIT:
addAll() takes an iterable
lstNames.addAll(["Dividends INR", "Payout Ratio % *", "Operating Cash Flow INR Mil", "Cap Spending INR Mil", "Free Cash Flow INR Mil"]);
put items inside a list.
You are using wrong comments
// comments the whole line as well as the closing }
/* */ to be used
case 'Dividends INR':
{/*Doing something.*/}
break;
case 'Payout Ratio % *':
{/*Doing something.*/}
break;

Related

Switch statement with closed-ranges covering full Float range

I am expecting the code below to cover the full Float range of which I use only a very small part just above 0.
My app however sometimes crashes in the field because it hits default: fatalError().
What could possibly be wrong here?
var value: Float // Between a little above 0 and about 15.
...
switch value
{
case ...3: return 0
case 3...10: return 1
case 10...: return 2
default: fatalError()
}
This switch will fall all the way through default for example if value is Float.nan or Float.signalingNaN, so it's technically possible for the app to legitimately crash at that point.
Consider adding some logging before crashing to check which value causes it to crash.
You have covered all cases except for the values whose eight exponent bits are all 1s. None of these are "Between a little above 0 and about 15", so your assumption is currently incorrect.
https://en.wikipedia.org/wiki/Single-precision_floating-point_format#Exponent_encoding

Switch/Case - When we can expect switch operator rework?

Hope Dart devs will add range of values and range checking in switch/case operators -
check if value is in range, check array elements, check multiple variables with same switch operator:
int i=27;
switch (i) {
case 1..30:
break;
default:
}
List<int> a=[1,5,7,14,25,30];
switch (a) {
case a.contains(5):
break;
case a[1..4]>0:
break;
}
switch ([a,i]) {
case i==5:
case a[1..4]>0:
break;
case a[i] is int:
break;
}
You're asking for something akin to pattern matching in C#. This isn't the place to be posting about your hopes for Dart's future. StackOverflow is a place to post issues you're having so that other people can help with specific answers.
That said, here's the situation. The Dart team has a lot on their plate for their roadmap across the various upcoming versions of Dart, and though I haven't looked through every post, I didn't see pattern matching among them. And if I'm to be perfectly honest here, I'd agree that pattern matching isn't nearly high enough a priority for them to focus on it at the expense of other features like, for instance, bringing nullable variables to full release.
If I were in the Dart team's shoes and I saw this proposal, I would ask how this feature benefits the language. What problems or inadequacies exist in the language that would be solved by pattern matching? Just about any application of a switch block with pattern matching could also be done with a series of if blocks:
Switch with pattern matching:
dynamic obj;
switch (obj) {
case obj == null:
print('obj is null');
break;
case obj is List:
print('length of obj is ${obj.length}');
break;
case obj is num && obj >= 5:
print('obj is greater than 5');
break;
default:
print('obj didn't match any conditions');
break;
}
If blocks:
dynamic obj;
if (obj == null) {
print('obj is null');
} else if (obj is List) {
print('length of obj is ${obj.length}');
} else if (obj is num && obj >= 5) {
print('obj is greater than 5');
} else {
print('obj didn't match any conditions');
}
(To put an even finer point on it, the if block approach results in fewer lines. What's more, the switch block requires a fair amount of boilerplate since each case or default requires a break statement.)
What's more, there isn't going to be any performance benefit, either. A switch block typically works like a hash table, reaching the desired code in O(1) constant time. However, this isn't possible with pattern matching, so in order to support this, languages with pattern matching support tend to pre-compile the match statement into something else entirely, thus losing the performance benefit of the hash table. This is evident in C# where pattern matching in a switch block is merely syntactic sugar for the equivalent set of if statements. (I'm not going to paste an example of it here because A] it's beside the point and B] it's too long, so you're going to have to trust me on this.)
So yeah, the only benefit to having this feature would be some subjective readability, and that's not nearly enough to justify it being a top priority addition to the language.
Now that being said, this is something that has been discussed here, here, and here. Pattern matching could have some usefulness when paired with other language features, such as first-class tuples and object destructuring. Unfortunately, Dart doesn't have many of those features either, and if we're talking about which features would benefit more, I would definitely rather have those features first.
TL;DR - Probably not any time soon.

tzfile format : handling of istd and isgmt

I'm trying to parse the tzfile (Olson) format on a Unix system. In the tzfile(5) man page it states the following:
Then there are tzh_ttisstdcnt standard/wall indicators, each stored
as a one-byte value; they tell whether the transition times
associated with local time types were specified as standard time or
wall clock time, and are used when a timezone file is used in
handling POSIX-style timezone environment variables.
Finally, there are tzh_ttisgmtcnt UTC/local indicators, each stored
as a one-byte value; they tell whether the transition times
associated with local time types were specified as UTC or local time,
and are used when a timezone file is used in handling POSIX-style
timezone environment variables.
Does this mean I can ignore isstd and isgmt and still get the correct times? In spot checking, this seems to be the case but in digging around in the C source files, I see unix makes some adjustments dependant on these values.
As requested above, I asked on the mailing list. The answer was to look in the code. So the relevant code is in zic.c (zone compiler) and glib's tzfile.c. Source code for both can be found on github at the time of this wring. The relevant code for zic.c is
switch (lowerit(*ep)) {
case 's': /* Standard */
rp->r_todisstd = true;
rp->r_todisgmt = false;
*ep = '\0';
break;
case 'w': /* Wall */
rp->r_todisstd = false;
rp->r_todisgmt = false;
*ep = '\0';
break;
case 'g': /* Greenwich */
case 'u': /* Universal */
case 'z': /* Zulu */
rp->r_todisstd = true;
rp->r_todisgmt = true;
*ep = '\0';
break;
Which says there are 3 possible cases: isstd = true && isgmt = false, both false and both true. So to see what is done with these flags, the relevant code in tzfile.c is
if (trans_type->isgmt)
/* The transition time is in GMT. No correction to apply. */ ;
else if (isdst && !trans_type->isstd)
/* The type says this transition is in "local wall clock time", and
wall clock time as of the previous transition was DST. Correct
for the difference between the rule's DST offset and the user's
DST offset. */
transitions[i] += dstoff - rule_dstoff;
else
/* This transition is in "local wall clock time", and wall clock
time as of this iteration is non-DST. Correct for the
difference between the rule's standard offset and the user's
standard offset. */
transitions[i] += stdoff - rule_stdoff;
So this seems to say that if isgmt is true we can ignore everything else. If it is false then if the previous transition was DST and the current one is not standard (i.e. case 'w' above, as it's also not gmt) apply the dst offset (the last one found in the file). Otherwise apply the standard offset.
Which seems to mean that glibc ignores the offsets in the individual tt_types and case 's'. I looked in localtime.c in the tz package and it worked the same way.
I can only conclude from all this that most of the information in the tzfile isn't actually used anywhere. Some of this may be due to POSIX requirements. If anyone can expand on the details below, please do. It would be nice to have this behaviour documented somewhere on the internet besides in C source code.

Exhaustive condition of switch case in Swift

The Apple documentation says
Every switch statement must be exhaustive. That is, every possible
value of the type being considered must be matched by one of the
switch cases.
So in new Xcode I have placed a code like this
println(UInt16.min); // Output : '0'
println(UInt16.max); // Output : '65535'
var quantity : UInt16 = 10;
switch quantity {
case 0...65535: //OR case UInt16.min...UInt16.max:
println();
default:
println();
}
Now if i remove the default section I get a compiler error:
Switch must be exhaustive
Do you want to add missing cases? Fix
So my question is for a case that I have mentioned as case 0...65535: have I not mentioned all the case values for an UInt16 ?? But still I am getting an error ?? Why am I getting this error, Did i miss something ??
Swift only truly verifies that a switch block is exhaustive when working with enum types. Even a switching on Bool requires a default block in addition to true and false:
var b = true
switch b {
case true: println("true")
case false: println("false")
}
// error: switch must be exhaustive, consider adding a default clause
With an enum, however, the compiler is happy to only look at the two cases:
enum MyBool {
case True
case False
}
var b = MyBool.True
switch b {
case .True: println("true")
case .False: println("false")
}
If you need to include a default block for the compiler's sake but don't have anything for it to do, the break keyword comes in handy:
var b = true
switch b {
case true: println("true")
case false: println("false")
default: break
}
Part of why you see that error because the compiler can't verify that switch is exhaustive without running code. The expression 0...65535 creates a ClosedInterval struct, and when the switch statement executes it has to ask that struct if the value quantity is in the interval. There's room for that to change at run time, so the compiler can't check it at compile time. (See the Halting Problem.)
More generally, the compiler can't detect an exhaustive switch for integer values — even if you add specific cases for every integer value (case 0: ... case 1: ... ... case 65535:), it doesn't know your switch is exhaustive. (Theoretically it could, though: consider filing a feature request about this if it's something you'd like to see.)
As it stands, there are two scenarios where Swift can detect completeness and allow you to omit the default clause: enums and value binding in tuples. #NateCook's answer covers enums — if you switch on an enum value and have a case in your switch for every case in the enum, you don't need a default. You also don't need a default label if you switch on a tuple and bind every possible combination of values, as seen in the Swift book:
switch anotherPoint {
case (let x, 0):
println("on the x-axis with an x value of \(x)")
case (0, let y):
println("on the y-axis with a y value of \(y)")
case let (x, y):
println("somewhere else at (\(x), \(y))")
}
You might generalize this rule as "if the type system knows about the possible values of your type, it can detect switch completeness", but the fact that there's a level on which the type system doesn't know the range of possible (e.g.) UInt32 values is sort of splitting hairs...
Swift 4.1. Either you need to specify all cases or Just include default block inside switch statement.
(As of Swift 4.2, and probably earlier): I have a helper function that converts a Bool? into the selectedSegmentIndex for a UISegmentedControl with 2 segments. If the value is nil then neither segment should be selected. My function uses a switch, which returns the appropriate segment index for true or false values, and uses this to explicitly test for the nil and satisfy the compiler's need for it to be exhaustive:
case nil: // only remaining possible value
fallthrough
default:
return UISegmentedControl.noSegment
Technically, the case nil: fallthrough isn't required because the default: will suffice, but this syntax may be useful if you want to explicitly test a value to make the code more self-documenting, or perhaps in another situation.
Check if your enum was initialised as an optional which could be either case or nil

Capture multiple blog posts and concatenate

I'm not sure what language fits this best (or if there's already a program for this), but here's what I basically want to do: When given a URL, I want it to go to that page, capture text between certain html tags (just one time per page), then click the "Next" button and move to the next page, (and repeat until finished). Then export the whole thing as a .pdf or something similar (a .txt could even work). It'd be useful if the program could print a horizontal rule between each post, but not required
I only need this to work once and, in fact, here's the blog I want to copy the posts from: http://www.trailjournals.com/entry.cfm?id=336394 (I basically just don't want to spend the time clicking through all of them).
I know some JavaScript, some basic regex, and some HTML along with a couple others that aren't really applicable here (and I'm a quick learner), so I'm here to learn, not just asking for someone to do something for me.
Thanks!
There's probably a better way to do it, but since I'm an engineering student (and Matlab is currently the programming language I'm best at), I decided to see if I could do it through there. And it worked.
Granted, some things could probably have been done better (I don't really know regex that well, so I used a lot of "findstr" instead).
clear;
clc;
fid=fopen('journals.txt','w');
fprintf(fid,'');
fclose('all');
fid=fopen('journals.txt','a');
id=input('Enter the starting id number: ','s');
loop=1;
while loop==1
clc;
url=strcat('http://www.trailjournals.com/entry.cfm?id=',id)
strContents=urlread(url);
f=findstr('</TABLE>',strContents);
f=f(1)+13;
l=findstr('<p>',strContents);
l=l(end)-5;
if f>l(end)
f=findstr('<blockquote>',strContents);
f=f(1)+14;
end
p=strContents(1,f:l)
if isempty(p)==1
cprintf('red','EMPTY ENTRY!\n');
return;
end
% disp(p);
% disp('------------');
% ques=input('Does this look good? (y/n): ','s');
% disp('------------');
%
% while ques=='n'
% firstword=input('Enter the first word: ','s');
% lastword=input('Enter the last word: ','s');
% f=findstr(firstword,strContents);
% l=findstr(lastword,strContents);
% p=strContents(1,f:l+length(lastword));
% disp(p);
% disp('------------');
% ques=input('Does this look good? (y/n): ','s');
% disp('------------');
% end
fprintf(fid,p);
fprintf(fid,'\n');
fprintf(fid,'\r\n\r\n-------------------------------------------\r\n\r\n');
%Next URL: next:next+6
next=findstr('">Next</a>',strContents);
if isempty(next)==1
break;
end
next=next(1);
next=next-6;
id=strContents(1,next:next+5);
url=strcat('http://www.trailjournals.com/entry.cfm?id=',id);
end
fclose('all');
cprintf('Green','The process has been completed\n');

Resources