Return true or Return false. It gives me an error - operator-keyword

Tring to do this, but it does not seem right. What is wrong?
return CrossSystemString.Substring(CrossSystemString.Length - 6) == "union " ? true : false;

Check the length of the string is greater than 6 or not
if(CrossSystemString.length > 6)
return CrossSystemString.Substring(CrossSystemString.Length - 6)
== "union" ? true : false;
else
return false;

Related

JS timeout causes eval exception

For some reason, one of my JS files is triggering an unsafe-eval Content Security Policy violation on my site. I thought this odd because there is no eval() anywhere in the file. The error happens on the following line:
setTimeout(callSpecific(), (lengthMF * (number.length + 2)));
The only thing I can see here is the arithmetic on the RHS that sets the timeout value. So, I tried:
setTimeout(callSpecific(), (parseInt(lengthMF) * (parseInt(number.length) + 2)));
Same thing. The variables themselves are not even strings - they are defined as:
var lengthMF = 150;
var number = ""; // yes, this is a string but number.length is not!
Why is this triggering a CSP violation? I have other setTimeout()s on the page and this seems to be the only problematic one. The weird thing is replacing the arithmetic expression temporarily with a constant (e.g. 50) does not cause the issue to go away.
If it's necessary, callSpecific() looks something like this:
function callSpecific() {
if (number == 0) {
operatorRing();
} else if (number.length == 2 && number.charAt(1) == 0) {
playReorder();
} else if (number.length == 3) {
//
} else if (number.length <7 || number.length > 11) {
//
} else if (number.length == 11 && (number.charAt(4) == 1 || number.charAt(4) == 0)) {
//
}
}

Returning Value in if else error

I have a dateFormatted and I am getting the date from API. I have got the value let's say 28 from 28th April 2018. So, I have to add the beside this 28 in Swift? Do anyone know this?
Else what I am trying is to set the values as "th" or "st" according to dates. I know the logics. I am just stuck with this:
let dateText = dateFormatterPrint.string(from: date)
if(dateText >= 4 && dateText <= 20) {
print("I am th")
}
Here it says, Binary operator '>=' cannot be applied to operands of type Int and String. I want to check for the value in this range?
Can anyone please help?
P.S. I got this and when printing I am getting values correctly, but when I return I get an error
if((count! >= 4 && count! <= 20) || (count! >= 24 && count! <= 30)){
return textVal = "I am th"
} else if(count! == 1 || count! == 21 || count! == 31) {
return textVal = "I am st"
} else if(count! == 2 || count! == 22) {
return textVal = "I am nd"
} else if(count! == 3 || count! == 23) {
return textVal = "I am rd"
} else {
print("I am known")
}
Use of unresolved identifier 'textVal'
Can anyone help?
The error occurs because you cannot return a variable which has never been declared
I recommend to use a switch statement
var dateText = dateFormatterPrint.string(from: date)
switch (dateText) {
case "1", "21", "31": dateText.append("st")
case "2", "22": dateText.append("nd")
case "3","23": dateText.append("rd")
default: dateText.append("th")
}
print(dateText)
It looks like you're trying to format an "ordinal number". The best way to do that is to configure a NumberFormatter to use a ordinal number style:
let ordinalNumberFormatter = NumberFormatter()
ordinalNumberFormatter.numberStyle = .ordinal
// for example...
ordinalNumberFormatter.string(from: 22) // "22nd"
ordinalNumberFormatter.string(from: 28) // "28th"
ordinalNumberFormatter.string(from: 31) // "31st"
We can't compare a String and an Int
if(dateText >= "4" && dateText <= "20")
{
print("I am th")
}

Cannot convert value of type 'String' to expected argument type 'Bool'

I am trying to write a function that will return true if the String str starts with a vowel. the following code will compile fine
func beginsWithVowel(str: String) -> Bool {
if(str.characters.count == 0){
return false
} else if(str.characters[str.startIndex] == "a"){
return true
}
return false
}
beginsWithVowel(str: "apple")
the problem is when I compare the first character to more than one character, for example
else if(str.characters[str.startIndex] == "a" || "e" || "i")
then I get the error 'Cannot convert the value of type 'String' to expected argument type 'Bool''
I've been fiddling with the code but no luck so far, any help would be appreciated. Thank you.
Swift cannot infer the logic you are trying to make. The logic to Swift becomes something like this:
if(str.characters[str.startIndex] == "a" || "e" || "i")
is equivalent to if(<Boolean expression> || "e" || "i")
is equivalent to if(<Boolean expression> || <String expression> || String expression)
An alternative solution can be:
if(["a", "b", "c"].contains(str.characters[str.startIndex])){
You should write it like this:
else if(str.characters[str.startIndex] == "a" || str.characters[str.startIndex] == "e" || str.characters[str.startIndex] == "i")
You get the error, because the compiler tries to convert both "e" and "i" to type Bool.
Instead of using if else switch will be more efficient:
func beginsWithVowel(str: String) -> Bool {
guard str.characters.count > 0 else {
return false
}
switch str.characters[str.startIndex]{
case "a","e","i","o","u":
return true
default:
return false
}
}
When you perform "a" || "e" || "i" you are comparing between the strings. Use this code:
if(str.characters[str.startIndex] == "a"
|| str.characters[str.startIndex] == "e"
|| str.characters[str.startIndex] == "i") {
// Your Code...
}
The boolean OR operator || expects boolean expressions.
So you would have to write EXPR == "a" || EXPR == "e" || EXPR == "i" where EXPR is the expression to get the first character.
However there is an easier solution (code is Swift 4)
func beginsWithVowel(str: String) -> Bool {
return "aeiou".contains(String(str.prefix(1)))
}
It considers also the empty string case.

What is this Swift ternary operator? A == B ? C : D

I inherited an iOS app that is crashing at this line (unexpected nil). What is your best interpretation of what is going on here?
indexPath.row.number == selectedItem ? cell.deselectStyle() : cell.dedeselectStyle()
The cell.deselectStyle() and cell.dedeselectStyle() functions don't return anything. I can't seem to find any information on what is going on here. selectedItem is a NSNumber!.
NSNumber could be nil leading to a crash if you try to access it. Add a guard to check that is not nil.
guard let s = selectedItem?.intValue else {
cell.dedeselectStyle
return
}
indexPath.row == s ? cell.deselectStyle() : cell.dedeselectStyle()
I've assumed it's safe to assume the cell is not selected if the NSNumber is nil, however you should really check the logic in your code to be sure.
This is a conditional statement. Think of it like an if statement:
if indexPath.row.number == selectedItem {
cell.deselectStyle()
} else {
cell.dedeselectStyle()
}
If the condition is true, the code between ? and : will be executed. If not, the code after the : will be called. You should know that the ? has nothing to do with Optionals.
In your case, selectedItem seems to be nil. Therefore, you need to either only execute the code if selectedItem is not nil, you could use an if let statement:
if let selectedItem = selectedItem {
indexPath.row.number == selectedItem ? cell.deselectStyle() : cell.dedeselectStyle()
}
Or, you could insert a default value that will be used instead of selectedItem if it is nil:
indexPath.row.number == (selectedItem ?? false) ? cell.deselectStyle() : cell.dedeselectStyle()
The code above will use either the value of selectedItem, or false, if selectedItem is nil. You can leave out the parentheses, I just put them there for better visualization.
I hope this helps :)
Probably The reason the crash is that selectedItem is nil; I think you misunderstand the difference between the ? for optionals and the ? for implementing the ternary operator.
The ternary operator has nothing to do with -implicitly- checking if the value is nil, you might need to implement a guard statement or if let (optional binding) before the step of doing the ternary operator comparison.
It should be similar to:
if let selectedItem = selectedItem {
indexPath.row.number == selectedItem ? cell.deselectStyle() : cell.dedeselectStyle()
} else {
print("selectedItem is nil!")
}
Or, if an early return required:
guard let selectedItem = selectedItem else {
print("selectedItem is nil!")
return
}
indexPath.row.number == selectedItem ? cell.deselectStyle() : cell.dedeselectStyle()
To make it more clear to you, check the following code snippet:
let nilValue: String! = nil
if nilValue == "test" { }
// fatal error: unexpectedly found nil while unwrapping an Optional value
// OR
let isValueTest: Bool = (nilValue == "test") ? true : false
// fatal error: unexpectedly found nil while unwrapping an Optional value
That's why you should unwrap the value before accessing it.
to better understand it, play in your Playground
func f0() -> Int { print(0); return 0 }
func f1() -> Int { print(1); return 1 }
func fa() -> String { print("a"); return "a" }
[true, false, true, true].forEach {
$0 ? f0() : f1() // warning: expression of type 'Int' is unused
}
[true, false, true, true].forEach {
_ = $0 ? f0() : f1() // OK
}
[true, false, true, true].forEach {
$0 ? f0() : fa() // error: result values in '? :' expression have mismatching types 'Int' and 'String'
}
[true, false, true, true].forEach {
_ = $0 ? ( 1 == f0()) : ( "A" == fa()) // OK
}

Swift on array.sort - Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions

I am downgrading Swift code from Xcode 8.3.1 to Xcode 7.3.1.
The Swift compiler of Xcode 7.3.1 raises
Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
while pointing on line zeroParameterAndPaths.sort {. The code was ok in Xcode 8.3.1.
What's wrong and how to fix it?
class NewConnectingSegmentZeroParameterAndPath {
let step : Int; // 0 = main, 1 = first outline, 2 = second outline
let parameter : CGFloat;
init(step: Int, parameter: CGFloat) {
self.step = step;
self.parameter = parameter;
}
}
var zeroParameterAndPaths : [NewConnectingSegmentZeroParameterAndPath] = [];
// ... some zeroParameterAndPaths .appendContentsOf calls
zeroParameterAndPaths.sort {
return $0.parameter < $1.parameter
|| ($0.parameter == $1.parameter
&& ($0.step == 1 || ($0.step == 0 && $1.step == 2))
)
};
You have two choices. One is simply to do what the error message suggests, i.e. pulling the complex bool apart into separate pieces:
zeroParameterAndPaths.sort {
let bless = ($0.parameter < $1.parameter)
let beq = ($0.parameter == $1.parameter)
let band = ($0.step == 0 && $1.step == 2)
let bor = ($0.step == 1 || band)
let beqandbor = (beq && bor)
return (bless || beqandbor)
};
The other is to provide an explicit in line giving the param types and result type:
zeroParameterAndPaths.sort {
(a:NewConnectingSegmentZeroParameterAndPath, b:NewConnectingSegmentZeroParameterAndPath) -> Bool in
return a.parameter < b.parameter
|| (a.parameter == b.parameter
&& (a.step == 1 || (a.step == 0 && b.step == 2))
)
};
You could also make your class a little bit more helpful and make it implement the condition. The compiler is much less likely to get confused in a function body than in a closure:
class NewConnectingSegmentZeroParameterAndPath {
let step : Int; // 0 = main, 1 = first outline, 2 = second outline
let parameter : CGFloat;
init(step: Int, parameter: CGFloat) {
self.step = step;
self.parameter = parameter;
}
func orderedBefore(_ other: NewConnectingSegmentZeroParameterAndPath) -> Bool
{
return parameter < other.parameter
|| parameter == other.parameter
&& (step == 1 || step == 0 && other.step == 2)
}
}
var zeroParameterAndPaths : [NewConnectingSegmentZeroParameterAndPath] = [];
// ... some zeroParameterAndPaths .appendContentsOf calls
zeroParameterAndPaths.sort { $0.orderedBefore($1) }
Apart from the issue of the type inference engine not being able to quickly resolve such complex bool expressions, such expressions are really hard to follow. I suggest you break it down into something simpler, like so:
zeroParameterAndPaths.sort {
if $0.parameter != $1.parameter { return $0.parameter < $1.parameter ]
if $0.step == 1 { return true }
if $0.step == 0 && $1.step == 2 { return true }
return false
};
There's my attempt at it. I'm not even sure if it's correct, the original expression is pretty hard to follow.