How do you fix Fatal error: index out of range? Swift - indexing

I know I have to return some sort of value in my code so it does not keep crashing with this thread error, but I can't figure it out. Please help! Here is the code- `
#IBAction func decideBttn(_ sender: Any) {
// if there is data in more than one Label randomly pick 1 out of 2
if valueLbl1.text?.isEmpty == false && valueLbl2.text?.isEmpty == false
{
var topics = [valueLbl1.text!, valueLbl2.text!]
pickTopic = Int(arc4random_uniform(UInt32(topics.count)))
topics.remove(at: pickTopic)
resultLbl.text = "\(topics[pickTopic])" //Where fatal error occurs
valueLbl1.text = ""
valueLbl2.text = ""
valueLbl3.text = ""
return
}
// if all 3 Labels are used button will randomly pick 1 out of 3
else if valueLbl1.text?.isEmpty == false && valueLbl2.text?.isEmpty == false && valueLbl3.text?.isEmpty == false
{
var topics = [ valueLbl1.text!, valueLbl2.text!, valueLbl3.text!]
pickTopic = Int(arc4random_uniform(UInt32(topics.count)))
topics.remove(at: pickTopic)
resultLbl.text = "\(topics[pickTopic])"
// resetting variable value
valueLbl1.text = ""
valueLbl2.text = ""
valueLbl3.text = ""
return
}

Related

How can I give if else if statement inside a AsEnumerable select

I am trying to give a conditional statement inside AsEnumerable select list. I have the following AsEnumerable select . Here I am trying to give the condition If IsRoleClocking = true then IsClockingEnabled should be true else the value of IsClockingEnabled must be depends the value of (Convert.ToInt32(row["IsClockingEnabled"]) . Please help to amend the existing code to consider IsRoleClocking also.
bool IsRoleClocking = true;
attendanceEntry.attendanceLogList = dt.AsEnumerable()
.Select(row =>
{
var p = new AttendanceLogModel
{
IsFlexibleDayOff = (Convert.ToInt32(row["IsFlexibleDayOff"]) == 1) ? true : false,
IsClockingEnabled = (Convert.ToInt32(row["IsClockingEnabled"]) == 1 ) ? true : false,
IsProtected = (Convert.ToInt32(row["IsProtected"]) == 1) ? true : false,
};
return p;
})
.ToList<AttendanceLogModel>();
return attendanceEntry;
}
I hope I got your question correctly :)
Does this help?
IsClockingEnabled = IsRoleClocking ? true :
(Convert.ToInt32(row["IsClockingEnabled"]) == 1 ) ? true : false;
update
Just noticed, it can be done much simpler:
IsClockingEnabled = IsRoleClocking || Convert.ToInt32(row["IsClockingEnabled"]) == 1;

Assert ONLY json .Net Object attributes name without values

Is that possible to assert just the json attribute names rather than values.
Actual:
{
CartId = 0
ConvertedAt = null
Currency = BankCurrency
{
BaseCurrencyCode = null
BaseToGlobalRate = 0
BaseToQuoteRate = 0
GlobalCurrencyCode = null
}
CustomerIsGuest = False
}
Expected :
{
CartId = 418
ConvertedAt = 2019-07-22 04:01:49
Currency = BankCurrency
{
BaseCurrencyCode = null
BaseToGlobalRate = 1
BaseToQuoteRate = 1
GlobalCurrencyCode = "AUD"
}
CustomerIsGuest = False
}
So when compare above both actual and expected should tally.
Basically I wanted to compare above json .Net objects and check attribute names (structure) is correct rather than attribute values in there. If you see above actual and expected structure is tallying but not the values inside. I have used below but it still complaining.
TheReturnedContentModelIs(new UserResponse())
Validation:
public async Task TheReturnedContentModelIs<T>(T expected)
{
var responseString = await ResponseMessage.Content.ReadAsStringAsync();
var actual = JsonConvert.DeserializeObject<T>(responseString);
actual.Should()
.BeEquivalentTo(expected,
opt => opt.Using<object>(_ => { })
.When(e => e.RuntimeType.IsValueType)
.Using<string>(_ => { })
.WhenTypeIs<string>());

VueJS & VUEX: Shortening JS Code

I love clean and simple code.
So I like to shorten these lines of javascript so they don't seem so cluttered.
My vuex-mutation code:
editEvent(state) {
if (
state.form.time !== '' &&
state.form.date !== '' &&
state.form.event !== '' &&
state.form.artist !== '' &&
state.form.organizer !== '' &&
state.form.location !== ''
) {
const event = {
time: state.form.time,
date: state.form.date,
event: state.form.event,
artist: state.form.artist,
organizer: state.form.organizer,
location: state.form.location
}
events.child(state.currentEventKey).update(event)
state.form.time = ''
state.form.date = ''
state.form.event = ''
state.form.artist = ''
state.form.organizer = ''
state.form.location = ''
state.currentEventKey = null
state.showForm = false
}
}
and here another one:
populateEventForm(state, payload) {
state.form.time = payload.event.time
state.form.date = payload.event.date
state.form.event = payload.event.event
state.form.artist = payload.event.artist
state.form.organizer = payload.event.organizer
state.form.location = payload.event.location
state.currentEventKey = payload.key
state.showForm = true
}
How can I improve this ?!??!
This is pseudo code for the most part. Somewhere store your common properties.
const props = ["time", "date", "event", "artist", "organizer", "location"]
Then use that in your functions.
function editEvent(state) {
// check to see if every property exists on the state
if (!props.every(p => state.form[p] !== '')) return
// build the event object
const event = props.reduce((acc, p) => acc[p] = state.form[p], {})
// I don't know where "events" comes from-- I left this alone
events.child(state.currentEventKey).update(event)
// clear each property
props.forEach(p => state.form[p] = '')
// clear your misc. props
state.currentEventKey = null
state.showForm = false
}
function populateEventForm(state, payload) {
props.forEach(p => state.form[p] = payload.event[p])
state.currentEventKey = payload.key
state.showForm = true
}
Please be advised, since you posted this as a Vue/Vuex question, you may need to use Vue.set instead of an indexer in cases like the event object being built. It's hard for me to tell from the limited code you posted. In that case it would be something like
const event = props.reduce((acc, p) => {
Vue.set(acc, p, state.form[p])
return acc
}, {})

dgrid custom sort with secondary sort column

I'm currently using a custom sort function on a dgrid (pasted below). It doesn't change sorting drastically, just sorts one particular column uniquely and sorts the others case-insensitive. I'd like to add a secondary sort by a column named "scheduled" to be added to the sort when any other column is sorted. I'm just not sure how to go about it. I've seen how to override the sort to sort by two columns, but not when a custom sort is in play. The secondary sort would always be there, not matter what other column is clicked.
For reference I'm running dojo 1.10 and dgrid 1.0. Data is coming from a RequestMemory DStore and I'd really rather this sort happen on the grid rather than back at the store level. Any help would be appreciated.
currGrid.on('dgrid-sort', function (event) {
event.preventDefault();
var sort = event.sort[0];
currGrid.set('sort', function (a, b) {
if (sort.property == "thisField") {
//special sort for thisField
if (a[sort.property] !== 'undefined' && typeof a[sort.property] == "string") {
var colorA = a[sort.property].split("|");
var aValue = colorA[0].toLowerCase();
}
if (b[sort.property] !== 'undefined' && typeof b[sort.property] == "string") {
var colorB = b[sort.property].split("|");
var bValue = colorB[0].toLowerCase();
}
if (String(aValue) == String(bValue)) {
var result = 0;
} else if (dojo.string.trim(aValue) == "") {
var result = true ? 1 : -1;
} else if (dojo.string.trim(bValue) == "") {
var result = true ? -1 : 1;
} else {
var result = aValue > bValue ? 1 : -1;
}
return result * (sort.descending ? -1 : 1);
} else {
//Sort for all other fields same as always (except toLowerCase)
if (a[sort.property] !== 'undefined' && typeof a[sort.property] == "string") {
var aValue = a[sort.property].toLowerCase();
} else {
var aValue = "";
}
if (b[sort.property] !== 'undefined' && typeof b[sort.property] == "string") {
var bValue = b[sort.property].toLowerCase();
} else {
var bValue = "";
}
var result = aValue > bValue ? 1 : -1;
return result * (sort.descending ? -1 : 1);
}
});
currGrid.updateSortArrow(event.sort, true);
});
currGrid.startup();
You could do something like below.
currGrid.on('dgrid-sort', function (event) {
event.preventDefault();
var sortSet = [];
sortSet.push(event.sort[0]);
sortSet.push({property: "scheduled"});
currGrid.set('sort', function (a, b) {
var aValue, bValue, result = 0;
for(var i = 0; i < sortSet.length; i++){
var sort = sortSet[i];
if (sort.property == "thisField") {
//special sort for thisField
if (a[sort.property] !== 'undefined' && typeof a[sort.property] == "string") {
var colorA = a[sort.property].split("|");
aValue = colorA[0].toLowerCase();
}
if (b[sort.property] !== 'undefined' && typeof b[sort.property] == "string") {
var colorB = b[sort.property].split("|");
bValue = colorB[0].toLowerCase();
}
if (String(aValue) == String(bValue)) {
result = 0;
} else if (dojo.string.trim(aValue) == "") {
result = true ? 1 : -1;
} else if (dojo.string.trim(bValue) == "") {
result = true ? -1 : 1;
} else {
result = aValue > bValue ? 1 : -1;
}
return result * (sort.descending ? -1 : 1);
} else {
//Sort for all other fields same as always (except toLowerCase)
if (a[sort.property] !== 'undefined' && typeof a[sort.property] == "string") {
aValue = a[sort.property].toLowerCase();
} else {
aValue = "";
}
if (b[sort.property] !== 'undefined' && typeof b[sort.property] == "string") {
bValue = b[sort.property].toLowerCase();
} else {
bValue = "";
}
//You need this check here
if(aValue != bValue){
result = aValue > bValue ? 1 : -1;
return result * (sort.descending ? -1 : 1);
}
}
}
return 0;
});
currGrid.updateSortArrow(event.sort, true);
});
currGrid.startup();
I have some concerns about your code, the variables result, aValue and bValue are all local within the if statement and yet they are being used outside the statement. It could result in wrong results if some other variables are defined with the same name in global space. So I have modified them.
So the second section you needed to check if aValue == bValue to return 0.

UITableview reusable cell issue swift

I have tableview in which each cell contains label,image and button.
My problem is when i disabled first cell and scroll table view 5th cell also disable
here is code
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! DetailTableViewCell
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
print(indexPath.row)
if indexPath.row == videoName.count
{
cell.video_name?.hidden = true
cell.artist_name?.hidden = true
cell.img?.hidden = true
cell.viewer?.hidden = true
cell.btn_add?.hidden = true
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
indicator.center = cell.contentView.center
if self.pageToken != ""
{
cell.contentView.addSubview(indicator)
indicator.startAnimating()
if videoIDArr.count == 25 || videoIDArr.count == 5
{
if check == 0
{
loadMoreMostPopularVideo()
}
else
{
loadMorePlaylistVideo()
}
}
}
}
else
{
indicator.stopAnimating()
cell.video_name?.hidden = false
cell.artist_name?.hidden = false
cell.img?.hidden = false
cell.viewer?.hidden = false
cell.btn_add?.hidden = false
tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
cell.video_name?.text = videoName[indexPath.row]
cell.artist_name?.text = artistName[indexPath.row]
cell.img?.sd_setImageWithURL(NSURL(string: self.thumbURL[indexPath.row]))
cell.viewer?.text = "\(viewerArr[indexPath.row]) views"
cell.btn_add.tag = indexPath.row
cell.btn_add?.addTarget(self, action: "addVideo:", forControlEvents: UIControlEvents.TouchUpInside)
// Disable cell code
if dataVideoName.contains(cell.video_name.text!)
{
cell.img.alpha = 0.50
cell.btn_add.alpha = 0.50
cell.viewer.alpha = 0.50
cell.video_name.alpha = 0.50
cell.artist_name.alpha = 0.50
cell.userInteractionEnabled = false
}
}
return cell
}
I have face this problem in morning
give me some suggestion to solve this problem
Thanks
You need enable cell codes for if indexPath.row == videoName.count {} to have cell's settings symmetrically
if indexPath.row == videoName.count {
....
// Enable cell code
if dataVideoName.contains(cell.video_name.text!)
{
cell.img.alpha = 1
cell.btn_add.alpha = 1
cell.viewer.alpha = 1
cell.video_name.alpha = 1
cell.artist_name.alpha = 1
cell.userInteractionEnabled = true
}
} else {
....
// Disable cell code
if dataVideoName.contains(cell.video_name.text!)
{
cell.img.alpha = 0.50
cell.btn_add.alpha = 0.50
cell.viewer.alpha = 0.50
cell.video_name.alpha = 0.50
cell.artist_name.alpha = 0.50
cell.userInteractionEnabled = false
}
}