can someone help me
i make button to retrieve previous Values
but i have two TextFiled
i must write in two TextFiled for work retrieve button
i do not want this happens
i want when I write in the first TextFiled, retrieve button work without any problem
but if i write in first TextFiled and second TextFiled at the same time i want retrieve button work without any problem
var previousValues: [String] = [String]();
var previousValues1: [String] = [String]();
previousValues.append(TextFailde.text ?? "error");
previousValues1.append(TextFilde1.text ?? "error");
if self.previousValues.count > 0 {
let previousValue = self.previousValues.removeLast()
let subtracted = (Int(self.lblZeroUs.text!)!) - (Int(previousValue)!)
self.lblZeroUs.text = "\(subtracted)"
}
else if self.previousValues1.count > 0 {
let previousValue = self.previousValues1.removeLast()
let subtracted2 = (Int(self.lblZeroThey.text!)!) - (Int(previousValue)!)
self.lblZeroThey.text = "\(subtracted2)"
}
and here the error
There are many errors, first of all you dont declare your properties with the first letter in uppercase, it's considered a bad practice.
Then, when you involve your properties in mathematical operations what do you need is to assign them a start value, especially if your code try to convert strings.
In Swift, you don’t need to write semicolons at the end of every statement.
I dont know the rest of your code, but your lines crash because you attempt to run mathematical operations using properties have nil as value.
This below it's just an example to avoid the first crashing for nil:
textFailde.text = "0"
textFilde1.text = "0"
previousValues.append(textFailde.text ?? String(0))
previousValues1.append(textFilde1.text ?? String(0))
self.lblZeroUs.text = String(0)
self.lblZeroThey.text = String(0)
if self.previousValues.count > 0 {
let subtracted = (Int(self.lblZeroUs.text!)!) - (Int(self.previousValues.last!))!
self.previousValues.removeLast()
self.lblZeroUs.text = "\(subtracted)"
}
else if self.previousValues1.count > 0 {
let subtracted2 = (Int(self.lblZeroThey.text!)!) - (Int(self.previousValues1.last!))!
self.previousValues1.removeLast()
self.lblZeroThey.text = "\(subtracted2)"
}
previousValues.append(TextFailde.text ?? "error");
previousValues.append(TextFilde1.text ?? "error");
You added to the same array twice, try changing the code to
previousValues.append(TextFailde.text ?? "error");
previousValues1.append(TextFilde1.text ?? "error");
Related
I have an array myarray and I am using a for loop to get a few information which I add to myarray. But next time the for-loop runs, I don't want to create a separate index, but instead the 2nd time and so on, I want to append the information to myarray[0].
How do I do that?
var myarray = [String]()
for var j in 0 < 12 {
// do some stuff
for var i in 0 ..< 10 {
let parta = json?["users"][j]["name"].string
let partb = json?["users"][j]["Lname"].string
let partc = json?["users"][j]["dob"].string
myarray.append("\(parta)-\(partb)-\(partc)---")
// Here when the for loop comes back again (i = 1) , i dont want to make
// myarray[1] , but instead i want myarray[0] ,
// having value like [parta-partb-partc--parta-partb-partc]
}
}
Basically what I am trying to do is, append the new name/lname/dob values at myarray[0] without affecting the current value/string at myarray[0].
You can insert single element and also add array as below.
Swift 5
var myarray = [String]()
myarray.insert("NewElement", at: 0)
myarray.insert(contentsOf: ["First", "Second", "Third"], at: 0)
If I understand your question correctly, you want to create one long string and add the new data always at the beginning of the string. One way to do that would be:
// Store somewhere
var myString = String()
for var i in(0..<10) {
let parta = json?["name"].string
let partb = json?["Lname"].string
let partc = json?["dob"].string
let newString = "\(parta)-\(partb)-\(partc)---")
newString.append(myString)
myString = newString
// Here when the for loop comes back again (i = 1) , i dont want to make
//myarray[1] , but instead i want myarray[0] ,
//having value like [parta-partb-partc--parta-partb-partc]
}
I have a text field where I can enter a double and it will be displayed on a label in the 2nd view controller. This value will be saved using UserDefaults. I am struggling to find what to do, to be able to then use this saved value and increase it with a new value entered in the text field.
i.e 1st time I enter 5; label displays 5. 2nd time I enter 3; label displays 8.
I tried to use the below if function, but this has not worked. When I enter a value for the 2nd time the label value goes back to 0, if then enter a value again, label is updated with the value entered.
func saveOne() {
UserDefaults.standard.set(weekOneTotal, forKey: "WEEKONE")
secondScreen.weekOneText = String(UserDefaults().double(forKey: "WEEKONE"))
}
func addCorrectSpend () {
guard let addAmount = convertAmount(input: enterField.text!) else {
print("Invalid amount")
return
}
if UserDefaults().double(forKey: "WEEKONE") == 0 {
weekOneTotal += addAmount
secondScreen.weekOneText = String(UserDefaults().double(forKey: "WEEKONE"))
saveOne()
}
else if UserDefaults().double(forKey: "WEEKONE") > 0 {
let defaultOne = UserDefaults.standard
defaultOne.set(defaultOne.double(forKey: "WEEKONE")+addAmount, forKey: "WEEKONE")
secondScreen.weekOneText = String(UserDefaults().double(forKey: "WEEKONE"))
saveOne()
}
}
To answer (quickly) why this is happening: You are setting the initial value in UserDetails.standard, which is correct, but then you are updating the value in a new UserDefaults() object each time.
You can also pare down your code a little bit as there is some unnecessary stuff in there. Ultimately you just need to add the new value to the existing value, so you don't really need to check if the existing value == 0. Here is an example of how I may refactor the above code:
func addCorrectSpend() {
guard let addAmount = convertAmount(input: enterField.text!) else {
print("Invalid amount")
return
}
//Get the existing total (will be 0 if none)
let weekOneAmount = UserDefaults.standard.double(forKey: "WEEKONE")
//Add the existing total to the new amount from your textField
let weekOneTotal = weekOneAmount + addAmount
//Update UserDefaults.standard to the new value
UserDefaults.standard.set(weekOneTotal, forKey: "WEEKONE")
//Set the text
secondScreen.weekOneText = "\(weekOneTotal)"
}
A different approach would be to utilize custom getter & setter for weekOneAmount, so that you can abstract away most of your calls and work with it as a normal variable.
var weekOneAmount: Double {
get {
return UserDefaults.standard.double(forKey: "WEEKONE")
}
set {
UserDefaults.standard.set(newValue, forKey: "WEEKONE")
}
}
Now, whenever you need to read or write, it behaves just like any other variable.
I am comparing whether a user should get a win or loss in their score column. I can't get the code to store the win/loss and then add 1 on top of it every time the if statement runs. Here is my if statement, followed by where i call it in the view did load. Cant seem to figure where I'm going wrong. thanks for the help!
viewDidLoad {
let dailyWinsDefault = UserDefaults.standard.integer(forKey: "dailyWinsDefault")
winsLabel.text = "\(dailyWinsDefault)"
print(dailyWinsDefault)
let dailyLossDefault = UserDefaults.standard.integer(forKey: "dailyLossDefault")
lossLabel.text = "\(dailyLossDefault)"
print(dailyLossDefault)
}
showWinLossVC.callbackForWinLoss = { result in
if result > 0.0 {
self.dailyWins += 1
UserDefaults.standard.set(self.dailyWins, forKey: "dailyWinsDefault")
self.winsLabel.text = String(self.dailyWins)
print(self.dailyWins)
}
else if result < 0.0 {
self.dailyLosses += 1
UserDefaults.standard.set(self.dailyLosses, forKey: "dailyLossDefault")
self.lossLabel.text = "\(self.dailyLosses)"
Couple of mistakes
Mistake 1:
Seems like you are setting integer in UserDefault for key dailyWinsDefault using statement
UserDefaults.standard.set(self.dailyWins, forKey: "dailyWinsDefault")
And you expect it to return you String when you retrieve it with
if let dailyWinsDefault = UserDefaults.standard.string(forKey: dailyWinsDefault)
Why will it not return nil ?
use
let dailyWinsDefault = UserDefaults.standard.integer(forKey: "dailyWinsDefault")
Mistake 2:
In your statement
if let dailyWinsDefault = UserDefaults.standard.string(forKey: dailyWinsDefault)
dont you think dailyWinsDefault should be in double quote as its a key and supposed to be string ?
try
let dailyWinsDefault = UserDefaults.standard.integer(forKey: "dailyWinsDefault")
EDIT:
As OP has updated code and now facing a issue with his updated code and requested for help updating my answer.
Couple of issues again
Mistake 1:
In entire ViewDidLoad method u never assigned the value retried from user defaults to property dailyWins and dailyLoses
viewDidLoad {
let dailyWinsDefault = UserDefaults.standard.integer(forKey: "dailyWinsDefault")
self.dailyWins = dailyWinsDefault //this is missing
winsLabel.text = "(dailyWinsDefault)"
print(dailyWinsDefault)
let dailyLossDefault = UserDefaults.standard.integer(forKey: "dailyLossDefault")
self.dailyLosses = dailyLossDefault //this is missing
lossLabel.text = "\(dailyLossDefault)"
print(dailyLossDefault)
}
Mistake 2:
Though not specific to your problem, you should always call super.viewDidLoad in your viewDidLoad unless u have a very firm reason for not doing so
That should help :)
I want change a label when the textfield contains one of the words in the two arrays, when I start the app, if I insert a word of the first array works. Then I insert a word of the second array and also this works, but if I insert again one word of the first array, the label don't change.
var one = ["word1", "word2", "word3"]
var two = ["word4", "word5", "word6"]
var count1 = 0
var count2 = 0
let s = textField.text?.lowercased()
for item in one{
if (s?.contains(item))!{
count1+=1
}
}
if count1 > 0{
label.text = "First array"
}
for item in two{
if (s?.contains(item))!{
count2+=1
}
}
if count2 > 0{
label.text = "Second array"
}
I'm not exactly clear on what you are asking, but one issue with the above code is that you do not reset count1 after the first loop - so if array one contains item, you will set label.text to "Second array" even if the second array does not contain item.
I'm assuming that count1 is declared outside the displayed code, as you don't declare it as a var within either loop. This means the scope includes both loops.
i guess you missed second counter for array two or you better try to figure another solution for this kind of tasks
var one = ["word1", "word2", "word3"]
var two = ["word4", "word5", "word6"]
var count1 = 0
var count2 = 0
let s = "word1"
var label = ""
for item in one{
if (s.contains(item)) {
count1+=1
}
}
if count1 > 0{
label = "First array"
}
for item in two{
if (s.contains(item)) {
count2+=1
}
}
if count2 > 0{
label = "Second array"
}
Found solution myself.
var one = ["word1", "word2", "word3"]
var two = ["word4", "word5", "word6"]
let s = label.text?.lowercased()
for item in one{
if (s?.contains(item))!{
label.text = "first array"
}
}
for item in two{
if (s?.contains(item))!{
label.text = "second array"
}
}
so I'm having this problem where I can't unwrap an optional for outputting it into the label, I've even tried just printing it in the console and it still gives me an optional
The code and array are in different files.
Code It's in a VC:
for var i = 0; i < stateName.count; i++ {
if tax.state == stateName[i][0] {
stateName[i][1] = Double(taxNumb.text!)!
print(stateName[i][1])
output.text = String(stateName[i][1])
}
}
Array Code I made this in an empty swift file:
var tax : Taxes? = nil
var stateName = [
["AK - Alaska", tax?.alaska!],
["AL - Alabama", tax?.alabama!],
["AR - Arkansas", tax?.arkansas!],
["AZ - Arizona", tax?.arizona!],
["CA - California", tax?.california!]
]
As I wrote in my comment to your previous question use the "Nil Coalescing" ?? operator:
output.text = String(stateName[i][1] ?? "not set")
Or using the alternate swift String magic
output.text = "\(stateName[i][1] ?? "not set")"
The operator returns the first value if it not nil, otherwise it returns the second value.