ow do I use the materialkit switch on and off in a case statement or in a if-else statement for a function? - cosmicmind

How do I use the materialkit switch on and off in a case statement or in a if-else statement for a function? It seems that the UIcontrol and Material Kit has two different syntax.

For Material, it is like this.
let materialSwitch = MaterialSwitch()
if .On == materialSwitch.switchState {
// Do something
} else {
// Do something else....
}

Related

How can I optimize switch-cases?

I've got a switch case like this:
def someString = 'hello1234bla'
// ...
switch (someString) {
case {it.contains('1234')}:
doSomething()
break
case {it.contains('2468')}:
doSomethingElse()
break
default:
throw new Exception("ERROR: Number not found")
break
}
This seems to be quite a lot of code for something so seemingly simple. All I want is to have different functions be executed when someString contains a specific substring. Is there no simpler way to do this, apart from maybe an if-else cascade?
This is pretty close to what the comments above suggest, but I'll write out a working example with indentation etc and perhaps it will be a bit more readable:
def someString = "hello1234bla"
def found = [
'1234': { println "do something" },
'2468': { println "do something else" }
].find { pattern, action ->
if (someString.contains(pattern)) { action(); true }
else false
}
if (!found) throw new Exception("ERROR: Number not found")
this executes the first matching action and throws an exception if no matches were found. If you need to execute an action for every match, replace the find call with a findAll call.
Another way of executing code based on a pattern in the string is the groovy String eachMatch method:
def someString = "hello1234blae"
someString.eachMatch(/1234/) { println "do something" }
someString.eachMatch(/2468/) { println "do something else" }
which uses regular expressions and runs the closure (the block in the curlies after the eachMatch call) once for every match. Thus:
someString.eachMatch(/e/) { println "runs twice" }
on the above string would execute twice as there are two 'e' characters in the string.

Knockout Binding with Multiple If statements

I am applying binding on a style and have succeeded in making the background colour change based on two scenarios. At present it says if the status is 'START', make the background #d10000, else make the background #93d667.
style: { background: ManagerStatus() == 'START' ? '#d10000' : '#93d667' }
I would like the following functionality:
If START, make #d10000
else if CONTINUE, make #93d667
else make #f7f7f7
How do I achieve these multiple case statements in Knockout binding?
Regards
Alexandra
Thanks guys. For future reference someone showed me that you can actually have multiple cases in the data-bind attribute:
{background: ManagerStatus() == 'START' ? '#d100000' : (ManagerStatus() == 'CONTINUE' ? '#93d667' : '#f7f7f7')}
Alexandra
You avoid filling your html with conditional logic and create a knockout computed observable in your viewmodel like so:
// or however your viewModel is currently set up.
var viewModel = {
ManagerStatus: ko.observable()
}
viewModel.statusBackground = ko.computed(function() {
status = this.ManagerStatus(),
switch (status) {
case "START": return "#d10000";
case "CONTINUE": return "#93d667";
default: return #f7f7f7;
}
}, viewModel);
html
style: { background: statusBackground }
You could do it by nesting two ternary operator expressions. But doing so it's not a good idea: it's much better to modify your View Model, and include a computed observable that returns the backgraound color. Something like this:
var vm = function() {
var self = this;
self.ManagerStatus = ko.observable();
self.backgroundcolor = ko.computed(function() {
ManagerStatus() == 'START'
? '#d10000' : ManagerStatus() == 'CONTINUE'
? '#93d667' : '#f7f7f7';
});
return self;
};
The binding would be like this:
style: { background: backgroundcolor }
Note that you in this case can use a pure computed, instead of a regular computed.
NOTE: I've shown how to write a nested ternary operator, and you could include it in the binding expression. But, if it looks ugly in a view model definition, it's even more ugly in a binding expression. In fact, I wouldn't write it like this in the view model definition. Much better to use chained if else or switch to make it more readable.

Is There a way to check if(do.condion=='11') in Groovy DSL

Is There a way to check if(do.condion=='11') in Groovy DSL.
if(object.member == '2') //then do my logic
I am not able to use ==. its not throwing any error it just going to next statement
If I'm understanding your DSL correctly, formatted for clarity it looks like this:
AcceptILPN {
input scanCase
if(workflowParameters.reserveVerificationModeParm.equals("1")) next AcceptSKUQuantity
if(workflowParameters.validateCarton.equals("1")) next AcceptOLPNOrTote
if(workflowDO.nextDtlPresent) next AcceptILPN else next AcceptPickCart
}
To see what's happening, here's the same code with a more formal syntax:
AcceptILPN {
input(scanCase)
if(workflowParameters.reserveVerificationModeParm.equals("1")) {
next(AcceptSKUQuantity)
}
if(workflowParameters.validateCarton.equals("1")) {
next(AcceptOLPNOrTote)
)
if(workflowDO.nextDtlPresent) {
next(AcceptILPN)
} else {
next(AcceptPickCart)
}
}
As you can see, even when the first if expression evaluates to true the following if blocks will execute because there's nothing (at least visible in the DSL) that exits the Closure prematurely. It seems you're looking for something like this:
AcceptILPN {
input(scanCase)
if(workflowParameters.reserveVerificationModeParm.equals("1")) {
next(AcceptSKUQuantity)
}
else if(workflowParameters.validateCarton.equals("1")) {
next(AcceptOLPNOrTote)
)
else if(workflowDO.nextDtlPresent) {
next(AcceptILPN)
} else {
next(AcceptPickCart)
}
}

How to use if let with another statement in swift?

If want to both assign a string and check that its not empty in Swift.
if let alternative3Text = attributes.stringForKey("choiceThree") && alternative3Text != "" {
// do stuff with alternative3Text
}
Is this possible in Swift, or do i have to do a nested if-statement?
Update: As of Swift 3 (Xcode 8), additional clauses are
separated by a comma, not by where:
if let alternative3Text = attributes.string(forKey: "choiceThree"),
alternative3Text != "" {
// do stuff with alternative3Text
}
Update: As of Swift 1.2 (Xcode 6.3 beta), you can combine
optional binding with additional conditions:
if let alternative3Text = attributes.stringForKey("choiceThree") where alternative3Text != "" {
// do stuff with alternative3Text
}
Using switch-case still works but is not necessary anymore for this purpose.
Old answer:
It is not possible with an if statement, but with switch.
A switch case can use a where clause to check for additional conditions
(documentation).
Assuming (from your question) that attributes.stringForKey("choiceThree") returns
String?, the following would work:
switch (attributes.stringForKey("choiceThree")) {
case .Some(let alternative3Text) where alternative3Text != "":
// alternative3Text is the unwrapped String here
default:
break
}
No, you can't require additional expressions to be true in an if let statement. You will need to add additional code to do this in either the form of a nested if statement as you've already mentioned, or in some other way. If your only requirement is to keep this statement looking clean and wouldn't mind moving some of the logic elsewhere, you could always make an extension to what ever type your attributes variable is to add this functionality.
Here's an example if attributes was an instance of NSUserDefaults. (just because it already contains a stringForKey() instance method.)
extension NSUserDefaults {
func nonEmptyStringForKey(key: String) -> String? {
let full = self.stringForKey(key)
return full != "" ? full : nil
}
}
And then use it like this
if let alternative3Text = attributes.nonEmptyStringForKey("choiceThree") {
// stuff
}

How does one return from a groovy closure and stop its execution?

I would like to return from a closure, like one would if using a break statement in a loop.
For example:
largeListOfElements.each{ element->
if(element == specificElement){
// do some work
return // but this will only leave this iteration and start the next
}
}
In the above if statement I would like to stop iterating through the list and leave the closure to avoid unnecessary iterations.
I've seen a solution where an exception is thrown within the closure and caught outside, but I'm not too fond of that solution.
Are there any solutions to this, other than changing the code to avoid this kind of algorithm?
I think you want to use find instead of each (at least for the specified example). Closures don't directly support break.
Under the covers, groovy doesn't actually use a closure either for find, it uses a for loop.
Alternatively, you could write your own enhanced version of find/each iterator that takes a conditional test closure, and another closure to call if a match is found, having it break if a match is met.
Here's an example:
Object.metaClass.eachBreak = { ifClosure, workClosure ->
for (Iterator iter = delegate.iterator(); iter.hasNext();) {
def value = iter.next()
if (ifClosure.call(value)) {
workClosure.call(value)
break
}
}
}
def a = ["foo", "bar", "baz", "qux"]
a.eachBreak( { it.startsWith("b") } ) {
println "working on $it"
}
// prints "working on bar"
I think you're working on the wrong level of abstraction. The .each block does exactly what it says: it executes the closure once for each element. What you probably want instead is to use List.indexOf to find the right specificElement, and then do the work you need to do on it.
If you want to process all elements until a specific one was found you could also do something like this:
largeListOfElements.find { element ->
// do some work
element == specificElement
}
Although you can use this with any kind of "break condition".
I just used this to process the first n elements of a collection by returning
counter++ >= n
at the end of the closure.
As I understand groovy, the way to shortcut these kinds of loops would be to throw a user-defined exception. I don't know what the syntax would be (not a grrovy programmer), but groovy runs on the JVM so it would be something something like:
class ThisOne extends Exception {Object foo; ThisOne(Object foo) {this.foo=foo;}}
try { x.each{ if(it.isOk()) throw new ThisOne(it); false} }
catch(ThisOne x) { print x.foo + " is ok"; }
After paulmurray's answer I wasn't sure myself what would happen with an Exception thrown from within a closure, so I whipped up a JUnit Test Case that is easy to think about:
class TestCaseForThrowingExceptionFromInsideClosure {
#Test
void testEearlyReturnViaException() {
try {
[ 'a', 'b', 'c', 'd' ].each {
System.out.println(it)
if (it == 'c') {
throw new Exception("Found c")
}
}
}
catch (Exception exe) {
System.out.println(exe.message)
}
}
}
The output of the above is:
a
b
c
Found c
But remember that "one should NOT use Exceptions for flow control", see in particular this Stack Overflow question: Why not use exceptions as regular flow of control?
So the above solution is less than ideal in any case. Just use:
class TestCaseForThrowingExceptionFromInsideClosure {
#Test
void testEarlyReturnViaFind() {
def curSolution
[ 'a', 'b', 'c', 'd' ].find {
System.out.println(it)
curSolution = it
return (it == 'c') // if true is returned, find() stops
}
System.out.println("Found ${curSolution}")
}
}
The output of the above is also:
a
b
c
Found c
Today I faced a similar problem while working with each closure. I wanted to break the flow of execution based on my condition but couldn't do it.
The easiest way to do in groovy is to use any() on a list instead of each if you wish to return a boolean based on some condition.
Good ole for loop still works in Groovy for your use case
for (element in largeListOfElements) {
if(element == specificElement){
// do some work
return
}
}

Resources