Using If statement to check against 3 possibilities - swift

I am wanting to compare three randomly generated numbers to see if any two of them are equal. I have an if statement that works but I would really like to combine the two else if statements into one if possible. I am thinking there has to be some way to use or but its only a binary operator. is there a way to use ? and make a ternary argument in one else if statement?
if aRand == bRand && bRand == cRand{
resultLabel.text = "3 out of 3"
} else if
(aRand == bRand || aRand == cRand) {
resultLabel.text = "2 out of 3"
} else if
(bRand == cRand) {
resultLabel.text = "2 out of 3"
} else {
resultLabel.text = "No Match"
}

Actually it's
if aRand == bRand || aRand == cRand || bRand == cRand
Here a swiftier expression
let rand = (aRand, bRand, cRand)
switch rand {
case let (a, b, c) where a == b && b == c : resultLabel.text = "3 out of 3"
case let (a, b, c) where a == b || a == c || b == c : resultLabel.text = "2 out of 3"
default : resultLabel.text = "No match"
}

Shorter way:
if (aRand == bRand && bRand == cRand) {
resultLabel.text = "3 out of 3"
} else if (aRand == bRand || bRand == cRand || aRand == cRand) {
resultLabel.text = "2 out of 3"
} else {
resultLabel.text = "No Match"
}

If I understand your algorithm correctly, you can avoid if altogether:
let aRand = 0
let bRand = 1
let cRand = 1
let allValues = [aRand, bRand, cRand]
let uniqueValues = Set(allValues)
let text: String
if (uniqueValues.count == allValues.count) {
text = "No match"
} else {
text = String(format: "%i out of %i", allValues.count - uniqueValues.count + 1, allValues.count)
}
print(text)
This will work for any number of values.

Related

This function has a nullable return type of 'String?' but ends without returning a value

I am trying to figure out why I get the Error in Title when adding if-Statements to my program. Without the if-statements everything works just fine. I hope someone can help me out :D Greetings
String? btmRechneranzeige(double? menge, double? prozent, String? btmittel,) {
// Add your function code here!
var m = menge;
var p = prozent;
double mengebtm = 0;
if (m != 0 && p != 0) {
mengebtm = m! * (p! / 100);
}
var result = mengebtm.toString();
String stoff = "";
if(btmittel == null){
return "...";
}
if (btmittel == "Amphetamin" && mengebtm >= 10) {
stoff = "Amphetaminbase übersteigt die nicht-geringe Menge";
} else {
if (btmittel == "Amphetamin" && mengebtm < 10) {
stoff = "Amphetaminbase übersteigt die nicht-geringe Menge nicht";
} else {return null;}
String output =
"Bei einer Menge von $result gramm handelt es sich um eine geringe Menge!";
//String result = nonono;
return output;
}
The brackets don't match up right, making paths that don't return anything. I suspect you want to change the line that says
} else {
to
} else
Although other things seem wrong as well. Like you don't even use the result of stoff
String? btmRechneranzeige1(double? menge, double? prozent, String? btmittel) {
var m = menge;
var p = prozent;
String stoff = "";
double mengebtm = 0;
if (m != 0 && p != 0) {
mengebtm = m! * (p! / 100);
}
var result = mengebtm.toString();
if (btmittel == null) {
return "...";
} else if (btmittel == "Amphetamin" && mengebtm >= 10) {
stoff = "Amphetaminbase übersteigt die nicht-geringe Menge";
} else if (btmittel == "Amphetamin" && mengebtm < 10) {
stoff = "Amphetaminbase übersteigt die nicht-geringe Menge nicht";
String output = "Bei einer Menge von $result gramm handelt es sich um eine geringe Menge!";
return output;
}
return null; // this line optional
}
You are missing a return at this if-statement "btmittel == "Amphetamin" && mengebtm >= 10"
So this would work:
String? btmRechneranzeige(double? menge, double? prozent, String? btmittel,) {
// Add your function code here!
var m = menge;
var p = prozent;
double mengebtm = 0;
if (m != 0 && p != 0) {
mengebtm = m! * (p! / 100);
}
var result = mengebtm.toString();
String stoff = "";
if(btmittel == null){
return "...";
}
if (btmittel == "Amphetamin" && mengebtm >= 10) {
stoff = "Amphetaminbase übersteigt die nicht-geringe Menge";
return "some text here..." // -> This is the added line!!
} else {
if (btmittel == "Amphetamin" && mengebtm < 10) {
stoff = "Amphetaminbase übersteigt die nicht-geringe Menge nicht";
} else {return null;}
String output =
"Bei einer Menge von $result gramm handelt es sich um eine geringe Menge!";
//String result = nonono;
return output;
}
} // You were also missing this bracket :D
When returning an instance of something make sure you add a return value (null is also a value) for each path, so every if (else) branch.

Is there any way to simplify complex if else statement in swift?

I have a long if else condition to assign a text to a UILabel. So i am looking for a better option/logic to write less number of lines.
Below is my condition,
if numberOfTeachers == 4 && numberOfStudents == 27 {
if String(interval.day! + 1) == "1" {
self.daysLabel.text = "1st"
self.testLabel.isHidden = true
self.subjectLabel.text = "Physics"
self.dayTitleLabel.text = "Today is your first day"
} else if String(interval.day! + 1) == "2" {
self.daysLabel.text = "2nd"
self.testLabel.isHidden = true
self.subjectLabel.text = "Chemistry"
self.dayTitleLabel.text = "Today is your Second day"
} else if String(interval.day! + 1) == "3" {
self.daysLabel.text = "3rd"
self.subjectLabel.isHidden = true
self.unitLabel.text = "Mathematics"
self.dayTitleLabel.text = "Today is your Third day"}
else if String(interval.day! + 1) == "4" {
self.daysLabel.text = "4th"
self.testLabel.isHidden = false
self.subjectLabel.text = "Physics"
self.dayTitleLabel.text = "Today is your fourth day" }
else if numberOfTeachers == 4 && numberOfStudents == 28 {
} else if numberOfTeachers == 4 && numberOfStudents == 29 {
} else if numberOfTeachers == 4 && numberOfStudents == 30 {
} else if numberOfTeachers == 5 && numberOfStudents == 27 {
} else if numberOfTeachers == 5 && numberOfStudents == 28 {
} else if numberOfTeachers == 5 && numberOfStudents == 29 {
} else if numberOfTeachers == 5 && numberOfStudents == 30 {
} else if numberOfTeachers == 6 && numberOfStudents == 27 {
} else if numberOfTeachers == 6 && numberOfStudents == 28 {
} else if numberOfTeachers == 6 && numberOfStudents == 29 {
} else if numberOfTeachers == 6 && numberOfStudents == 30 {
} else if numberOfTeachers == 7 && numberOfStudents == 27 {
} else if numberOfTeachers == 7 && numberOfStudents == 28 {
} else if numberOfTeachers == 7 && numberOfStudents == 29 {
} else if numberOfTeachers == 7 && numberOfStudents == 30 {
}
there are atleast 4 more conditions inside every if condition like (4,27), (4,28) , (5,27), (5,28)....so on.
So this whole condition is getting too long.
You could nest the if conditions like:
if numberOfTeachers == 4
{
if numberOfStudents == 29 {}
else if ...
}
else if ...
You could also use a switch statement which is a great alternative for long chains of if-else:
switch numberOfTeachers
{
case value 4:
// handle number of students
case value 5:
...
default:
// error?
}
Edit as Martin R noted, one could also use:
switch (numberOfTeachers, numberOfStudents)
{
case (4, 27):
// handle number of students
case (5, 28):
...
default:
// error?
}

Continue in Scala for loops

How do i convert below Java code to scala and use continue in for loop, this program remove minimum number of extra closed parenthesis in a given string
input : lee(t(c)o)de)
output : leet(t(c)o)de
public String minRemoveToMakeValid(String s){
StringBuilder sb =new StringBuilder();
in open =0;
for (char c : s.toCharArray()){
if(c == '('){
open++
}
else if(c == ')'){
if(open == 0) continue;
open --;
}
sb.append(c)
}
return sb
}
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
import util.control.Breaks._
val searchMe = "peter piper picked a peck of pickled peppers"
var numPs = 0
for (i <- 0 until searchMe.length) {
breakable {
if (searchMe.charAt(i) != 'p') {
break // break out of the 'breakable', continue the outside loop
} else {
numPs += 1
}
}
}
println("Found " + numPs + " p's in the string.")
Try it: https://scastie.scala-lang.org/R9sr95WESLyiKamCHHUVdQ
Im able to get it worked using below code
def minRemoveToMakeValid(s: String): String = {
var open = 0
val sb = new StringBuilder
for (c <- s.toCharArray) {
breakable {
if (c == '(') open += 1
else if (c == ')') {
if (open == 0)break
open -= 1
}
sb.append(c)
}
}
var result = new StringBuilder()
for(i<-sb.length()-1 to 0 by -1)
{
breakable{
open-=1
if(sb.charAt(i) == '(' && open >0) break
result.append(sb.charAt(i))
}
}
result.reverse.toString()
}

swift if condition with multiple cases

In c# or others we can use this in IF
ex.
if((a=1 && b=2)
(c=2 && d=3)
){}
using ( inside ( to check bool in that statement.
But in swift
I'm trying to make something like this.
func IsWorkDay() -> Bool {
if (monWorkYN == "Y" , weekday == 2)
|| (tueWorkYN == "Y" , weekday == 3)
|| (wedWorkYN == "Y" , weekday == 4)
{
return true
}
}
But the ( ) doesn't work here. Is there a way to do this?
In this case you have to use the && operator, with a comma the compiler treats the expression in parentheses as a tuple.
And please name functions (and variables) with starting lowercase letter
func isWorkDay() -> Bool {
if (monWorkYN == "Y" && weekday == 2)
|| (tueWorkYN == "Y" && weekday == 3)
|| (wedWorkYN == "Y" && weekday == 4)
{
return true
}
return false
}
or simpler
func isWorkDay() -> Bool {
return (monWorkYN == "Y" && weekday == 2)
|| (tueWorkYN == "Y" && weekday == 3)
|| (wedWorkYN == "Y" && weekday == 4)
}
You can use this property instead of your function
var isWorkDay: Bool {
return (monWorkYN == "Y" && weekday == 2)
|| (tueWorkYN == "Y" && weekday == 3)
|| (wedWorkYN == "Y" && weekday == 4)
}
Resource
You can check this for learn more
Swift Documentation

Can somebody shorten this code?

I just finished creating a program (I am a beginner at this programming stuff) Now I might be doing this the total wrong way or my logic might not be the greatest at programming but any help would be amazing I will post my code so far below
This code is used when a button is clicked, the button will send a text then the textbox will get the text.
if (txt1.Text == "")
{
txt1.Text = "J";
btn1.Visible = false;
}
else if (txt1.Text != "")
{
if (txt2.Text == "")
{
txt2.Text = "J";
btn1.Visible = false;
}
else if (txt2.Text != "")
{
if (txt3.Text == "")
{
txt3.Text = "J";
btn1.Visible = false;
}
else if (txt3.Text != "")
{
if (txt4.Text == "")
{
txt4.Text = "J";
btn1.Visible = false;
}
else if (txt4.Text != "")
{
if (txt5.Text == "")
{
txt5.Text = "J";
btn1.Visible = false;
}
else if (txt5.Text != "")
{
if (txt6.Text == "")
{
txt6.Text = "J";
btn1.Visible = false;
}
else if (txt6.Text != "")
{
if (txt7.Text == "")
{
txt7.Text = "J";
btn1.Visible = false;
}
else if (txt7.Text != "")
{
if (txt8.Text == "")
{
txt8.Text = "J";
btn1.Visible = false;
}
else if (txt8.Text != "")
{
}
}
}
}
}
}
}
}
You need to get all of these text cases into an array for the following loop to work (I have called the array 'txt' here). Based on what you have written this loop should do the same thing as your code but I'm not sure if that's what you really want to do. Your code is setting a single text box to "J" and then hiding your button only if every preceding text field is not an empty string (This will include any of the fields set to null, for example). The conditional then exits.
`for (int i = 0; i < txt.Length; i++) {
if(txt[i] != "") {
continue;
}
else if(txt[i] == "") {
txt[i] = "J";
btn1.Visible = false;
break;
}
}
Note: I don't know whether this works for C# 3 or not (it should). Try it.
First, you should put all of your text fields into an array:
TextField[] textFields = { txt1, txt2, txt3, txt4, txt5, txt6, txt7, txt8, };
Then, loop through the text fields to find a text field that has no text in it:
foreach (TextField tf in textFields) {
if (tf.Text == "") {
}
}
After we find it, we want to set its text to "J" and make btn1 invisible. Since we already found the text field, we don't need to continue the loop anymore, so we break:
tf.Text = "J";
btn1.Visible = false;
break;
If this doesn't work in C# 3, just update to C# 5 or 6 alright?