swift if condition with multiple cases - swift

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

Related

Error running simulation — An unknown error occurred

{
"__name__":"/databases/(default)/documents/users/mfBBtfSX91YS9mXrkmEDTksA0712/sold/mfBBtfSX91YS9mXrkmEDTksA0712-hanSW0s5MxOOENWnc5T1cLinekj2/invoice/WhdEi2W83GtjDjowi6MV",
"id":"WhdEi2W83GtjDjowi6MV",
"data":{
"id":"db1a01a0-4da5-11ec-a579-c31f34aa6119",
"total":80,
"quotations":[
{
"id":"c595e610-46ab-11ec-b8ad-d56159e1778c",
"title":"anda",
"measuremntUnit":"kg",
"rate":35,
"quantity":2,
"isSelected":false,
"index":1
},
{
"id":"c595e610-46ab-11ec-b8ad-d56159e1778c",
"title":"biscuit",
"measuremntUnit":"packet",
"rate":10,
"quantity":1,
"isSelected":true,
"index":7}
],
"sellerEmail":"ku1438693#gmail.com",
"sellerUserId":"mfBBtfSX91YS9mXrkmEDTksA0712",
"sellerDisplayName":" Lila Kunwar",
"buyerUserId":"hanSW0s5MxOOENWnc5T1cLinekj2",
"buyerDisplayName":"saugat thapa",
"buyerEmail":"nexus.saugat26#gmail.com",
"sellerPhotoUrl":"https://lh3.googleusercontent.com/a/AATXAJ",
"buyerPhotUrl":"https://lh3.googleusercontent.com/a/AATXAJ"
}}
i am trying to check whether above data can insert into firestore given that the following is the security rule. however i get error Error running simulation — An unknown error occurred.
match /users/{userId}{
match /sold/{soldId}/{document=**}{
function isAuthed(){
return request.auth != null && request.auth.uid == userId;
}
function isSeller(){
return request.auth.uid == resource.data.sellerUserId ||
request.auth.uid == resource.data.buyerUserId;
}
function isApproved() {
return request.resource.data.isApproved == false;
// || request.resource.data.reviewed == "false"
}
function quotations(){
return request.resource.data.quotations;
}
function isOtherThanQuotations(){
return
isValidStringInput(request.resource.data.buyerUserId) &&
isValidStringInput(request.resource.data.buyerEmail) &&
isValidStringInput(request.resource.data.buyerPhotoUrl) &&
isValidStringInput(request.resource.data.buyerDisplayName) &&
isValidStringInput(request.resource.data.sellerUserId)&&
isValidStringInput(request.resource.data.buyerEmail) &&
isValidStringInput(request.resource.data.buyerPhotoUrl) &&
isValidStringInput(request.resource.data.buyerDisplayName) &&
isValidNumber(request.resource.data.total) &&
// isApproved() &&
request.resource.data.createdAt == request.time;
}
function isSelected() {
return request.resource.data.isSelected == false;
// || request.resource.data.reviewed == "false"
}
function isValidQuotation(item) {
return quotations()[item].keys().hasAll(
[
'title',
'rate',
'quantity',
'measuremntUnit',
'isSelected',
'index',
])
&& isValidStringInput(quotations()[item].title, 200)
&& isValidNumber(quotations()[item].rate)
&& isValidNumber(quotations()[item].quantity)
&& isValidStringInput(quotations()[item].measuremntUnit, 200)
&& isValidNumber(quotations()[item].index)
&& isSelected();
}
function isValidStringInput(input, maxSize) {
return input is string
&& input.size() > 0
&& input.size() <= maxSize;
}
function isValidNumber(input) {
return input is int
|| input.matches('^[0-9]+$');
}
allow read: if isSeller();
allow write: if isAuthed()
&& quotations().size() >= 1
&& quotations().size() <= 10
&& isOtherThanQuotations()
&& isValidQuotation(0)
&& (quotations().size() < 2 || isValidquotation(1) )
&& (quotations().size() < 3 || isValidquotation(2) )
&& (quotations().size() < 4 || isValidquotation(3) )
&& (quotations().size() < 5 || isValidquotation(4) )
&& (quotations().size() < 6 || isValidquotation(5) )
&& (quotations().size() < 7 || isValidquotation(6) )
&& (quotations().size() < 8 || isValidquotation(7) )
&& (quotations().size() < 9 || isValidquotation(8) )
&& (quotations().size() < 10 || isValidquotation(9) )
&& (quotations().size() < 11 || isValidquotation(10) );
}
}
is it becase i have too too many functions? right now myconcern is with create only.
is it becasue the id doesnt have security rule to validate? i tried providing validation for id as well but the error still persist. i need more than 10 map in an array but this is for simplicity of testing process.

Unable to create a constant value of type <object>. Only primitive types or enumeration types are supported in this context

I am using the following code:
public static Grid.GridResult GetExamDetailsForGrid(Grid.GridFilter Filter, int userid, int _user_roleid, int selectedYear,string Tin,string Measure, DateTime? Startdate, DateTime? Enddate)
{
Grid.GridResult _examsEntered = new Grid.GridResult();
using (var entity = new PQRSEntityContainer())
{
((IObjectContextAdapter)entity).ObjectContext.CommandTimeout = 120;
var Measureid = 0;
if(!string.IsNullOrEmpty(Measure))
{
Measureid = entity.tbl_Lookup_Measure.Where(m => m.CMSYear == selectedYear && m.Measure_num == Measure)
.Select(v => v.Measure_ID).FirstOrDefault();
}
var _username = CurrentUser.UserName;
var npi = FileProcessBL.getNPINumber(userid);
var cmsYear = selectedYear != 0 ? selectedYear : 0;
var Newtin= string.IsNullOrEmpty(Tin) ? null : Tin;
var NewStartdate = Startdate ==null ? null : Startdate;
var NewEnddate = Enddate == null ? null : Enddate;
var NewMes= string.IsNullOrEmpty(Measure) ? null : Measure;
var liDetails = (from ex in entity.tbl_Exam.Where(i => i.Physician_NPI == npi && i.CMS_Submission_Year == cmsYear
&& i.Exam_TIN == (Newtin==null?i.Exam_TIN:Newtin)
&& i.Exam_Date >= (NewStartdate == null ? i.Exam_Date : NewStartdate)
&& i.Exam_Date <= (NewEnddate == null ? i.Exam_Date : NewEnddate))
from exmes in entity.tbl_Exam_Measure_Data.Where(i => i.Exam_Id == ex.Exam_Id
&& i.Measure_ID== (Measureid == 0 ? i.Measure_ID : Measureid) ).DefaultIfEmpty()
from nume in entity.tbl_lookup_Numerator_Code.Where(nume => exmes.tbl_Lookup_Measure.Measure_ID == nume.tbl_Lookup_Measure.Measure_ID && exmes.Numerator_response_value == nume.Numerator_response_Value).DefaultIfEmpty()
join sc in entity.tbl_Lookup_Data_Source on ex.DataSource_Id equals sc.DataSource_Id
where exmes.Exam_Id != null
select new MesCasesGrid
{
NPI = ex.Physician_NPI,
TIN = ex.Exam_TIN == null ? "" : ex.Exam_TIN,
ExamID = ex.Exam_Id,
//MeasureID = exMes.Measure_ID,
MeasureID = (exmes != null) ? exmes.Measure_ID : 0,
MeasureNum = (exmes != null) ? exmes.tbl_Lookup_Measure.Measure_num : null,
CPTCode = (exmes != null) ? exmes.Denominator_proc_code : null,
///NumeratorCode = (exmes!=null)?exmes.tbl_Lookup_Measure.tbl_lookup_Numerator_Code.Select(i=>i.Numerator_Code).FirstOrDefault():null,
NumeratorCode = nume.Numerator_Code,
Created_Date = ex.Created_Date,
ExamDate = ex.Exam_Date,
UniqueExamID = ex.Exam_Unique_ID,
PatientGender = (ex.Patient_Gender == "M" ? "Male" : ex.Patient_Gender == "F" ? "Female" : ex.Patient_Gender == "O" ? "Other" : ex.Patient_Gender == "U" ? "Unknown" : ""),
PatientID = ex.Patient_ID,
isEncrypt = ex.IsEncrypt,
PatientAge = ex.Patient_Age,
StatusDesc = (exmes != null) ? exmes.tbl_Lookup_Measure_Status.Status_Desc : null,
///Type =ex.DataSource,
Type = sc.DataSource,
cmsYear = ex.CMS_Submission_Year
}).Distinct().ToList();
if (_user_roleid == Constants.FacilityAdminID || _user_roleid == Constants.FacilityUserID || _user_roleid == Constants.RegistryAdminID
|| _user_roleid == Constants.SuperCorporateAdminID || _user_roleid == Constants.CorporateAdminID || _user_roleid == Constants.ServiceUserID) // jira-579
{
var facilityTins = entity.sp_getFacilityTIN(_username).Select(x => x.TIN).ToList();
liDetails = liDetails.Where(i => facilityTins.Contains(i.TIN)).Select(x => x).Distinct().ToList();
}
var value = Convert.ToBoolean(1);
foreach (var item in liDetails)
{
if (item.isEncrypt == value && item.PatientID != null)
{
try
{
var patidDecrypt = AesHelper.Decrypt256(item.PatientID);
item.PatientID = patidDecrypt;
}
catch (Exception ex)
{
}
}
}
return _examsEntered;
}
}
I have recently added the following code above method:
i.Measure_ID == && i.Measure_ID== (Measureid == 0 ? i.Measure_ID : Measureid)
When adding the highlighted code to this method I am getting following error:
:Error in RecordEnteredGridBind()
System.NotSupportedException: Unable to create a constant value of type 'DAL.Entities.tbl_Exam_Measure_Data'. Only primitive types or enumeration types are supported in this context.
at System.Data.Objects.ELinq.ExpressionConverter.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.NewArrayInitTranslator.<>c__DisplayClass1_0.<TypedTranslate>b__0(Expression e)
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator3.Validate(IEnumerable1 argument, String argumentName, Int32 expectedElementCount, Boolean allowEmpty, Func3 map, Func2 collect, Func3 deriveName)
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator3.Validate()
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.CreateExpressionList(IEnumerable1 arguments, String argumentName, Boolean allowEmpty, Action2 validationCallback)
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateNewCollection(IEnumerable`1 elements, DbExpressionList& validElements)
I have tried lot of ways but not working. So, Can anyone help me?

My logic for seeing if a user has won a tic-tac-toe match isn't working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Below is some code to check if somebody has won on a tic tac toe board. (board[0] - board[8] represent the tic tac toe board from top to bottom, left to right):
func checkWin(board: [Int]) -> Bool{
if board[0] != 0 {
if board[0] == board[1] && board[1] == board[2] {
return true
} else if board[0] == board[3] && board[3] == board[6] {
return true
}
} else if board[4] != 0 {
if board[1] == board[4] && board[4] == board[7] {
return true
} else if board[3] == board[4] && board[4] == board[5] {
return true
} else if board[2] == board[4] && board[4] == board[6] {
return true
} else if board[0] == board[4] && board[4] == board[8] { //
return true
}
} else if board[8] != 0 {
if board[2] == board[5] && board[5] == board[8] { //
return true
} else if board[6] == board[7] && board[7] == board[8] { //
return true
}
}
return false
}
However, the three lines with // at the end will not return true even if the conditions are met. I have noticed that they all share board[8], however I know this is not a problem with the storyboard, as if I hard code a win that satisfies one of faulty conditions it still doesn't work. Can anyone see what's going wrong?
Your logic is flawed. Once you check with the outer ifs, you have committed to just checking a few of the possible cases.
For instance, if space 0 is not empty, then you are only checking cases 0-1-2 and 0-3-6, but you aren't checking 0-4-8 so you'll miss that possibility. The 0-4-8 case is handled inside the first else if case, but you'll never get there if board[0] != 0.
You can fix this by using 3 ifs instead of the else ifs.
func checkWin(board: [Int]) -> Bool{
print(board)
if board[0] != 0 {
if board[0] == board[1] && board[1] == board[2] {
return true
} else if board[0] == board[3] && board[3] == board[6] {
return true
}
}
if board[4] != 0 {
if board[1] == board[4] && board[4] == board[7] {
return true
} else if board[3] == board[4] && board[4] == board[5] {
return true
} else if board[2] == board[4] && board[4] == board[6] {
return true
} else if board[0] == board[4] && board[4] == board[8] { //
return true
}
}
if board[8] != 0 {
if board[2] == board[5] && board[5] == board[8] { //
return true
} else if board[6] == board[7] && board[7] == board[8] { //
return true
}
}
return false
}
a little bit more compact:
func checkWin(board: [Int]) -> Bool{
let checks = [
//rows
[0,1,2],
[3,4,5],
[6,7,8],
//columns
[0,3,6],
[1,4,7],
[2,5,8],
//cross
[0,4,8],
[2,4,6]
]
for check in checks{
if board[check[0]] != 0
&& board[check[0]] == board[check[1]]
&& board[check[1]] == board[check[2]]
{
return true
}
}
return false
}
better to get also the winner-id or 0 for no winner:
func getWinner(board: [Int]) -> Int{
let checks = [
//rows
[0,1,2],
[3,4,5],
[6,7,8],
//columns
[0,3,6],
[1,4,7],
[2,5,8],
//cross
[0,4,8],
[2,4,6]
]
for check in checks{
if board[check[0]] != 0
&& board[check[0]] == board[check[1]]
&& board[check[1]] == board[check[2]]
{
return board[check[0]]
}
}
return 0
}
or if you like to put it in an enum:
enum Winner {
case none
case player(id: Int)
}
func checkWin(board: [Int]) -> Winner{
let checks = [
//rows
[0,1,2],
[3,4,5],
[6,7,8],
//columns
[0,3,6],
[1,4,7],
[2,5,8],
//cross
[0,4,8],
[2,4,6]
]
for check in checks{
if board[check[0]] != 0
&& board[check[0]] == board[check[1]]
&& board[check[1]] == board[check[2]]
{
return .player(id: board[check[0]])
}
}
return .none
}

Using If statement to check against 3 possibilities

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.

Swift: Error when updated Xcode: 'could not find overload for '&&' that accepts the supplied arguments'

I just updated to the non beta version of Xcode 6 (finally) and, coming from beta 5, got a few errors that I didn't get before, one being "could not find overload for '&&' that accepts the supplied arguments"
I am following a tutorial here and from another question, I know that this error is because "the expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions."
I'm a beginner; how do I break up an expression into sub-expressions?
My code:
func checkForWin(){
//first row across
var youWin = 1
var theyWin = 0
var whoWon = ["Lost":0,"Won":1]
for (key,value) in whoWon {
if ((plays[6] == value && plays[7] == value && plays[8] == value) || //across the bottom
(plays[3] == value && plays[4] == value && plays[5] == value) || //across the middle
(plays[0] == value && plays[1] == value && plays[2] == value) || //across the top
(plays[6] == value && plays[3] == value && plays[0] == value) || //down the left side
(plays[7] == value && plays[4] == value && plays[1] == value) || //down the middle
(plays[8] == value && plays[5] == value && plays[2] == value) || //down the right side
(plays[6] == value && plays[4] == value && plays[2] == value) || //diagonal
(plays[8] == value && plays[4] == value && plays[0] == value)){//diagonal
userMessage.hidden = false
youLabel.hidden = false
userMessage.text = "\(key)!"
done = true;
}
}
}
To break it up, you just need to add more ()s. Like this:
if (((plays[6] == value) && (plays[7] == value) && (plays[8] == value)) ||
((plays[3] == value) && (plays[4] == value) && (plays[5] == value)) ||
((plays[0] == value) && (plays[1] == value) && (plays[2] == value)) ||
((plays[8] == value) && (plays[4] == value) && (plays[0] == value)))