I am new in Swift and have a small question.
I want to build a function which can return values of different types based on the conditions. What return type should I use?? Below is the function. I use "??" as the placeholder. Can anybody help to change the "??" with correct return type?? Thanks!!
fun Req_amt() -> ?? {
if let input_amt = readLine() {
if let amount = Float(input_amt) {
return amount
} else {
return "Bad number."
}
} else {
return "Bad input."
}
}
You could return a Float? with nil to signify an error in general, or you could return a Float but with throws and throw an Error to give further specific info such as “Bad number” or “Bad input”. It sounds like the latter is what you want here.
I'm getting the error "missing return in function expected to return 'Bool'" but I can't figure out why.
func isPrime(_ number: Int) -> Bool {
for primeDivisors in 2..<number {
if number % primeDivisors == 0 {
return true
} else {
return false
}
}
}
isPrime(13)
Your prime checker is incorrect, because the very first iteration of the loop returns a value. You have to go through the entire loop before deciding that the number is prime.
func isPrime(_ number: Int) -> Bool {
for primeDivisors in 2..<number {
if number % primeDivisors == 0 {
return false
}
}
return true
}
Note that this code is inefficient, because it continues checking divisibility more times than it is necessary: you can stop checking upon reaching square root of number.
It's complaining because not all code paths end up returning something. What happens if number is less than 2? Then your for loop, and the return statements inside it, will never be called, and there's no return that happens after the for loop finishes.
I have this simple function that return some value based on the passed argument:
function GetParam($fileName)
{
if($fileName.ToLower().Contains("yes"))
{
return 1
}
elseif($fileName.ToLower().Contains("no"))
{
return 2
}
else
{
return -1
}
}
I want to call this script from another script and get its return value, in order to decide what to do next.
How can I do that ?
You have to dot source the script where the GetParam function is defined to expose it to the other script:
getparam.ps1
function GetParam($fileName)
{
if($fileName.ToLower().Contains("yes"))
{
return 1
}
elseif($fileName.ToLower().Contains("no"))
{
return 2
}
else
{
return -1
}
}
other.ps1
. .\getparam.ps1 # load the function into the current scope.
$returnValue = GetParam -fileName "yourFilename"
Note: Consider using approved Verbs and change your function name to Get-Param. Also you can omit the return keyword.
Swift 2's guide mentions that you can end program execution of an if statement. I personally have never used break with if-statement.
A break statement ends program execution of a loop, an if statement,
or a switch statement...When a break statement is followed by the
name of a statement label, it ends program execution of the loop, if
statement, or switch statement named by that label.
In what situation would one be using break in an if-statement? This language feature seems useless.
TEST:
if (true) {
break TEST
}
For example if you want to describe a number (with Strings) with reference to sets of numbers (even/rational/negative numbers) your code could look something like this:
if condition1 {
// code
if condition2 {
// code
if condition3 {
// code
if condition4 {
//code
}
}
}
}
You can achieve the same logic but without the nested ifs by refactoring it (using guard):
OuterIf: if condition1 {
// code
guard condition2 else { break OuterIf }
// code
guard condition3 else { break OuterIf }
// code
guard condition4 else { break OuterIf }
// code
}
// reads even better when breaking out of "do"
scope: do {
guard condition1 else { break scope }
// code
guard condition2 else { break scope }
// code
guard condition3 else { break scope }
// code
guard condition4 else { break scope }
// code
}
You might think that this can also be achieved with switch and fallthrough but this doesn't work with "normal" cases because it checks all conditions and if one condition is met all following conditions aren't even evaluated.
So the fallthough has to be called conditionally.
This does work but I isn't very readable not to mention its "beauty":
let x = 4
switch x {
case _ where condition1:
// code
if condition2 { fallthrough }
case _ where false:
// code
if condition3 { fallthrough }
case _ where false:
// code
if condition4 { fallthrough }
case _ where false:
// code
break
default: break
}
Using break with an if statement seems a bit contrived, and I can't think of a place where style would demand it. It does, however, save an extra level of indentation when skipping the latter portion of an if statement in an if-else clause, which can be useful for deeply nested loops.
In other languages, a popular (and/or controversial) idiom is to use labels for handling errors in deeply nested functions. For example, one might want to break out of a loop on error, like this:
func testBreak3() {
// doesn't compile!!!
let a = false, b = true, x = 10, y = 20, err = true
if !a {
if b && x > 0 {
if y < 100 {
if err {
break handleError
}
// some statements
} else {
// other stuff
}
}
}
return // avoid error handling
handleError:
print("error")
// handle the error
}
But in Swift (I'm using 2.0 as a reference), labels are different than with other languages; the above example doesn't compile for two reasons: The label isn't declared yet when it's used, and the label must be directly associated with a do, while, if, or case statement. Furthermore, break within an if or do statements requires that statement to be labeled. We can fix this as follows, although the changes make the solution less attractive due to additional tracking via the errorFlagged variable, making refactoring more attractive:
func testBreak() {
let a = false, b = true, x = 10, y = 20, err = true
var errorFlagged = false
nestedIf: if !a {
if b && x > 0 {
if y < 100 {
if err {
errorFlagged = true
break nestedIf
}
// some statements
} else {
// other stuff
}
}
}
// skip handling if no error flagged.
if errorFlagged {
print("error")
// handle error
}
}
I know this is old topic, but just now I used break and it was needed.
So my example
I have array of objects.
When user taps on a cell, i.parameter becomes True for the object in that cell.
I need to know when all the objects in the array have i.parameter = True , that's the condition to stop the game.
func forTimer(){
for i in array {
if i.parameter == false {
break
}
}
}
timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(forTimer), userInfo: nil, repeats: true)
Even if one i.parameter = false, I do not need to check the rest of the array.
This function is called every millisecond, so I will not have to check the whole array every millisecond.
I have var i have assigned it value 12.90 i want that if variable has value 12.90 then it may execute if other wise else
if (appDelegate.p_ClinInf_Yes_NV_InModel==12.90) {
}
else{
}
but it runs every time else statement
Try this
if (appDelegate.p_ClinInf_Yes_NV_InModel == 12.90F) {
}
else{
}
Comparing a float and a double for equality would not yield expected results due to their precision.