expressin is not an integer constant expression - ios

I am using switch case into my method like in screenshot
I already done with Enumeration but how can I directly pass int constant into case??
I googled it but I found it with Enumeration
Please help me with it

If that's all the functionality you want to achieve then you should write something like this:
if (index.row == value) {
// logic when it's that row
} else {
// default case
}
What you tried to do is simply not possible, see the two questions linked by Martin R in the comments.

Related

Return/break out of infinite foreach in kotlin

For class I have to make a program that calculates the birthday problem
Now I'm having trying to learn kotlin at the same time and I'm having trouble with a little snippet of code:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#outForeach
}
}
outForeach#
sum += checkSet.size
As you can see I'm trying to do this with an infinite sequence. Kotlin doesn't accept this as outForeach is an unresolved reference. But this doesn't work either:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#forEach
}
}
sum += checkSet.size
This will just start the forEach loop again. Is there a way to implement something as a forEachUntil or so?
p.s. I'm aware that this looks a lot like this question: 'return' doesn't jump out of forEach in Kotlin It's just that I don't really get the answers and I don't know if its applicable here. Also a way to implement forEachUntil seems for me to be far more elegant
Alternatives you may want to consider instead of first:
using a simple while without body:
while (checkSet.add(Random.nextInt(n))); // <- that semicolon is required! otherwise you execute what is coming next within the while
using run with a label:
run outForeach#{
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#outForeach
}
}
}
maybe also takeWhile might be helpful. In this specific case however it is surely not (as it would check against the checkSet and leave us with a sequence that isn't consumed... but if the condition would be different, it may make sense to consider something like take, takeWhile, takeLast, etc.):
generateSequence { Random.nextInt(n) }
.takeWhile(checkSet::add) // as said: for this specific condition it doesn't make sense...
.forEach { /* do nothing except consume the sequence */ } // the same values you added to the set would be available in this step of course
I think I found the solution myself:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.first { !checkSet.add(it) }
sum += checkSet.size
Basically use the function first() and keep returning false until you want to get out of the loop. And just drop the return of the function first()

how do i declare variables, compare them and then use them inside a function

i am developing an ea that requires me to compare the high of previous 2 bars and whichever one is higher, use that as a stop loss value.
same for opposite side trades, i need to compare previous 2 lows and use the lower one as stop loss value.
what i am doing is this:-
void onTick()
{
static int ticket=0;
double ab=(//calculation for ab);
double de=(//calculation for de);
if(Low[1]<Low[2])
double sll=Low[1];
if(Low[1]>Low[2])
double sll=Low[2];
if(buy logic comes here)
{
double entryPrice=////////;
double stoploss=sll-xyz;
double takeprofit=entryPrice+((entryPrice-stoploss)*3);
ticket = OrderSend(Symbol(),...entryPrice,stoploss,takeprofit,.....);
}
if(ticket == false)
{
Alert("Order Sending Failed");
}
}
the problem is i am not able to reference the values of sll and get an error message saying "sll undeclared identifier"
i am fairly new to programming and would appreciate if someone can help me out with this.
I have added most of the code for you to understand the logic.
you would have to declare them outside the scope of the if statements if you want to use variables anywhere else so instead of doing that take a look at this
double sll; // declare sll outside the if statements
if(Low[1]<Low[2])
sll=Low[1];
if(Low[1]>Low[2])
sll=Low[2];
if(buy logic comes here)
{
bool res = OrderSend(..........);
}
Judging by what you wrote, it looks like you may be using res somewhere else too which then you need to define outside of the if statement because scoping.

run function depending on passed integer in swift

I want to run different functions depending on selected level Integer
so if selected level is 1 then runfunc1(), if 2 then runfunc2()...
I know this is possible using if else
if levelselected == 1 {
runfunc1()
} else if levelseletecd == 2 {
runfunc2()
// ... and so on
}
Is there any better way than this, perhaps something like this
runfunc%i(),levelselected // I know its not correct but something similar
I dont want to write new code for every level, so any better way?
You can use something like:
var levelSelected = 0 //
var selector = Selector("runFunc\(levelSelected)")
if self.respondsToSelector(selector) {
NSThread.detachNewThreadSelector(selector, toTarget: self, withObject: nil)
}
You could have an array or dictionary of functions. A dictionary might be nicer since the logic for checking if the level is valid is a lot simpler:
let funcs = [1: runfunc1, 2: runfunc2]
if let funcToRun = funcs[levelselected] {
funcToRun()
}
However, you won't be able to easily dynamically build a function name from strings and numbers without using #objc functionality.
(except in the sense that you could make the key to the dictionary a string of the function name, but you still have to build the dictionary using actual function names determined at compile time)
That said, you can add to the funcs variable from elsewhere in the code so it does mean to can "hook up" new levels without changing this dispatching logic.
Not the exact solution you are looking for but this can make it easier :
Declare an array of the desired functions:
var levelFunctions: [()->()] = [runfunc1, runfunc2, runfunc3]
This syntax declares an array of functions that have zero argument and return nothing. You initialize this array with the required function names and then execute the desired function using the levelselected variable:
levelFunctions[levelselected]() // Or levelselected-1 if the variable is not zero-based
EDIT:
As Airspeed Velocity mentioned in the comment and his answer you should make sure the level is in the array bounds.
I prefer to create a function, for example runFuncFromLevel::Int -> (() -> Void). runFuncFromLevel return a proper function that you need.
func runFuncFromLevel(level: Int) -> () -> Void
{
switch level
{
case 1: return runfunc1
case 2: return runfunc2
default: return {}
}
}

What is the recommended way to break out of a block or stop the enumeration?

So, I just realize that break is only for loop or switch.
Here's my question: Is there a recommended way to break out of a block? For example:
func getContentFrom(group: ALAssetsGroup, withAssetFilter: ALAssetsFilter) {
group.enumerateAssetsUsingBlock { (result, index , stop) -> Void in
//I want to get out when I find the value because result contains 800++ elements
}
}
Right now, I am using return but I am not sure if this is recommended. Is there other ways? Thanks folks.
return is fine, block concept is similar to function, so returning is okay.
If you want to stop the current iteration of the enumeration, simply return.
But you say:
I want to get out when I find the value because result contains 800++ elements
So, that means that you want to completely stop the enumeration when you find the one you want. In that case, set the boolean value that the pointer points to. Or, a better name for that third parameter would be stop, e.g.:
func getContentFrom(group: ALAssetsGroup, withAssetFilter: ALAssetsFilter) {
group.enumerateAssetsUsingBlock() { result, index, stop in
let found: Bool = ...
if found {
//I want to get out when I find the value because result contains 800++ elements
stop.memory = true
}
}
}

Indexed TableViews not displaying after upgrade to MT 4.0

After upgrading to MT 4.0, my TableViews that previously were displaying indexes on the right hand border are no longer working. The tableview still displays in sections and works properly, but the index is not displaying.
I have these three methods defined in my UITableViewSource, and all three appear to be working:
public override string[] SectionIndexTitles(UITableView tableView)
public override int SectionFor(UITableView tableView, string Title, int atIndex)
public override string TitleForHeader(UITableView tableView, int section)
Is anyone else having this problem? Is this a bug with MT 4.0?
This is a known bug.
It appears that UITableView is not retaining the returned array, you can use
the following to work around this issue while we investigate it further:
NSArray array;
[Export ("sectionIndexTitlesForTableView:")]
public NSArray SectionTitles (UITableView tableview)
{
if (array == null) {
string[] titles = new string[RowsInSection(tableview, 0)];
for (int index = 0; index < titles.Length; index++)
titles[index] = index.ToString();
array = NSArray.FromStrings (titles);
}
return array;
}
This was showing to me just numbers (index for each item of the section 0 (like A letter of the index), so I found that must change this to:
NSArray array;
[Export ("sectionIndexTitlesForTableView:")]
public NSArray SectionTitles (UITableView tableview)
{
if (array == null)
{
array = NSArray.FromStrings (SectionIndexTitles(tableview));
}
return array;
}
To all people who don't get the workaround to work correctly:
For me it was because I left the MonoTouch override method SectionIndexTitles in there - as soon as I removed it (or in my case renamed it so it can be called from the workaround), it worked as described :)
Getting the same problem, but the above fix did not work, I am sure it is probably something simple that I am doing wrong. The below methods are part of a UITableViewSource. All working as it was before MT 4.0, however the textual Index is not appearing. Debug output listed below the code shows that SectionTitles is not being called. Any thoughts on how this differs from the solution above, and how to get it working? Happy to start a new thread on this, but thought that it might be useful to have more information on this question instead.
NSArray array;
[Export ("sectionIndexTitlesForTableView:")]
public NSArray SectionTitles(UITableView tableview)
{
Debug.WriteLine("SectionTitles");
if (array == null)
{
array = NSArray.FromStrings(SectionIndexTitles(tableview));
}
return array;
}
public override string[] SectionIndexTitles(UITableView tableView)
{
Debug.WriteLine("SectionIndexTitles");
var sectionIndexTitles = Root.Sections.Select(section => section.IndexTitle ?? string.Empty);
var applySectionIndexTitles = sectionIndexTitles.Any (sectionIndexTitle => !string.IsNullOrEmpty (sectionIndexTitle));
foreach (string s in sectionIndexTitles)
{
Debug.WriteLine(s);
}
Debug.WriteLine("applySectionIndexTitles = " + applySectionIndexTitles);
return applySectionIndexTitles ? sectionIndexTitles.ToArray () : null;
}
Debug output:
SectionIndexTitles
A
B
C
D
E
F
G
H
J
K
L
M
N
O
P
R
S
T
W
applySectionIndexTitles = True
Wow, the answers here are a extremely misleading. Where do I start?
First, why are the examples using a backing NSArray? Why not a string [] for the backing data? Just because the method returns a NSArray doesn't mean you have to back it with an NSArray. Yikes. Why would you use an NSArray unless you have to. You don't have to here.
Second, realistically, I always store my index titles in a backing string []. That is normal use I'd say. Why wouldn't you do that anyway? The answers here make it sounds like it's a special case or something where you have to store it. As far as I know you are always responsible for doing that anyway. And another example relying on the cells to get data... Why on earth? If you can't simply use an array then get a clue that your array is out of scope or something.
Also, some people mentioned to not override as you normally would. Ummm... I don't know about that. That completely contradicts all the monotouch code I've seen. I've seen a lot of examples do both and it makes sense. Look at some of the template UIViewController constructors. The internal calls that explicitly reference selectors will need the selector. Normally you wouldn't need one but in this case apparently something internal is broken referencing the selector. That is NOT a reason to ditch overriding it as you normally would. You still need to override it in case you have some external call that came from your own managed code. You should absolutely still override it. Unless you always explicitly referencing selectors in YOUR code... then keep it overriden.
Anyway, a lot of this is my general monotouch understanding and I could be wrong. I mean, I don't know... I'm seriously not trying to criticize. I just had to comment because it looks like to me there is A LOT of bad information in this thread and I'm hoping this post will help someone who might be getting misinformed.

Resources