Continuously append to the end of an array - ios

Each time I press a button I am trying to append that new number to the end of my array. I have tried a ton of different things, but I can't quite get it.
I have tried the append, insert, creating an empty array and so much more.
import UIKit
import Foundation
var num1 = 0
class ViewController: UIViewController {
#IBAction func button(_ sender: UIButton) {
var digitCounts = Array(repeating: 0, count: 10)
var number_list = [1,2,3]
if num1 >= 0 {
digitCounts.insert(3, at: num1)
print(digitCounts)
number_list.append(num1)
num1 += 1
print(num1)
print(number_list)
}
}
the result would look like
starting array [1,2,3] after button pressed first time [1,2,3,4] after
button pressed second time [1,2,3,4,5] after button pressed third time
[1,2,3,4,5,6]

Ok now that you've shown the full code I can see the problem. You are creating new arrays every-time you click the button, but are storing num1 outside of this function.
Try this:
import UIKit
import Foundation
class ViewController: UIViewController {
var num1 = 0
var digitCounts = Array(repeating: 0, count: 10)
var number_list = [1,2,3]
#IBAction func button(_ sender: UIButton) {
if num1 >= 0 {
digitCounts.insert(3, at: num1)
print(digitCounts)
number_list.append(num1)
num1 += 1
print(num1)
print(number_list)
}
}
By storing the arrays as properties of the class, instead of inside the function, they will persist through multiple clicks

you have to make you array global and make changes as follow
import UIKit
import Foundation
var num1 = 0
class ViewController: UIViewController {
var number_list = [1,2,3]
#IBAction func button(_ sender: UIButton) {
var number = number_list.last ?? 0
number += 1
number_list.append(number)
print(number_list)
}
}

If you're not multithreading, a simple solution is to remember the last number instead of having to check the last element in the array:
class ViewController: UIViewController {
var number_list = [1, 2, 3]
var num1 = 3
#IBAction func button(_ sender: UIButton) {
number += 1
number_list.append(number)
print(number_list)
}
}

First of all you should declare var number_list as a ViewController's property:
class ViewController: UIViewController {
var number_list = [1,2,3]
}
Otherwise var number_list with it's default value will be created each time when button(_ sender:) is calling.
And use the following handler for your button:
#IBAction func button(_ sender: UIButton) {
number_list += number_list.last.flatMap { [$0+1] } ?? []
print(number_list)
}
All code in this post was tested in Xcode 10.2.1. I used Swift 5.

Related

Saving Int to UserDefaults when starting at 0

I want the code to start a var num = 0. Then after every button hit num increases by 1. The problem that I am running into is that when I switch view controllers and come back to this one it starts at 0 again. Num can only starts at 0 one tie when is loaded for the first time. I want to use userdefults to save the number so no matter what the score will always increase.
import UIKit
class ViewController: UIViewController {
var num = 0
let defaults = UserDefaults.standard
#IBAction func press () {
num += 1
defaults.set(num, forKey: "num")
}
}
You have to initialize num from UserDefaults.
Add this to viewDidLoad:
num = defaults.integer(forKey: "num")
Or simply update your var num = 0 line to:
var num = UserDefaults.standard.integer(forKey: "num")
You can't use your defaults variable in this case.
Call synchronize() immediately after your set data in user defaults, so it save it.
set already set value back to num in View Will Appear as View Will Appear will be called on Pop to this View from other Screen.
See Code
import UIKit
class ViewController: UIViewController {
var num = 0
let defaults = UserDefaults.standard
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
num = defaults.integer(forKey: "num")
print("Value of number from defaults \(num)")
}
#IBAction func press () {
num += 1
defaults.set(num, forKey: "num")
defaults.synchronize()
}
}

How to terminate (not segue) just one view in Swift

I am wondering how to make just 1 view terminate in iOS. I am making an app such that in the viewDidLoad() it generates 52 random strings and appends them to an array. I have it so that when you shake the device, it will perform a segue.
The problem with this is that it keeps the items in the array that I mentioned earlier. This means that when it does the user goes into that view again, it will still have the 52 random strings, plus when it goes through the viewDidLoad function, it will append 52 more strings, so if the user doesn't terminate the whole entire app, but just segues out of the view and goes back in, there will be 104 strings and not 52.
I don't want the above to happen in my app, so I am wondering how you could just terminate this one view while also performing a segue so that this problem won't happen.
Here is some code from my app:
These are the arrays I had:
var theCardsTopPlayerHas = [""]
var theCardsBottomPlayerHas = [""]
var theCardsThatWork = ["2_of_clubs", "2_of_diamonds", "2_of_hearts", "2_of_spades", "3_of_clubs", "3_of_diamonds", "3_of_hearts", "3_of_spades", "4_of_clubs", "4_of_diamonds", "4_of_hearts", "4_of_spades", "5_of_clubs", "5_of_diamonds", "5_of_hearts", "5_of_spades", "6_of_clubs", "6_of_diamonds", "6_of_hearts", "6_of_spades", "7_of_clubs", "7_of_diamonds", "7_of_hearts", "7_of_spades", "8_of_clubs", "8_of_diamonds", "8_of_hearts", "8_of_spades", "9_of_clubs", "9_of_diamonds", "9_of_hearts", "9_of_spades", "10_of_clubs", "10_of_diamonds", "10_of_hearts", "10_of_spades", "jack_of_clubs2", "jack_of_diamonds2", "jack_of_hearts2", "jack_of_spades2", "queen_of_clubs2", "queen_of_diamonds2", "queen_of_hearts2", "queen_of_spades2", "king_of_clubs2", "king_of_diamonds2", "king_of_hearts2", "king_of_spades2","ace_of_clubs", "ace_of_diamonds", "ace_of_hearts", "ace_of_spades"]
Here is what the viewDidLoad method has:
struct shuffledVar {
static var shuffled = [String]();
}
override func viewDidLoad() {
super.viewDidLoad()
upperLabelNumber.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
//MARK: - Shuffling Cards
for _ in 1...52 {
let shuffledCardList = Int(arc4random_uniform(UInt32(theCardsThatWork.count)))
let the_card = theCardsThatWork[shuffledCardList]
print("\(the_card)")
shuffledVar.shuffled.append(the_card)
theCardsThatWork.remove(at: shuffledCardList)
print("Finished Card")
}
theCardsTopPlayerHas = Array(shuffledVar.shuffled[0...25])
theCardsBottomPlayerHas = Array(shuffledVar.shuffled[26...51])
print("")
print(shuffledVar.shuffled)
print("")
print(theCardsTopPlayerHas)
print("")
print(theCardsBottomPlayerHas)
}
This is the code that segues the view:
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
performSegue(withIdentifier: "friendToDashboard", sender: self)
}
Thank you!
The problem is that you are using a static var to store your array of strings.
To solve this problem there are several solutions depending on what you need. Here there are a couple of solutions:
Solution 1
If you really need to keep the shuffled array as a Singleto, then you can empty the shuffled array in the viewDidLoad method:
override func viewDidLoad() {
super.viewDidLoad()
shuffledVar.shuffled = []
upperLabelNumber.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
...
}
Solution 2
If you do not need to keep the shuffled array as a Singleton, then you can modify it as follows:
struct shuffledVar {
var shuffled = [String]();
}
var shuffled = shuffledVar()
override func viewDidLoad() {
super.viewDidLoad()
upperLabelNumber.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
//MARK: - Shuffling Cards
for _ in 1...52 {
let shuffledCardList = Int(arc4random_uniform(UInt32(theCardsThatWork.count)))
let the_card = theCardsThatWork[shuffledCardList]
print("\(the_card)")
shuffled.shuffled.append(the_card)
theCardsThatWork.remove(at: shuffledCardList)
print("Finished Card")
}
theCardsTopPlayerHas = Array(shuffled.shuffled[0...25])
theCardsBottomPlayerHas = Array(shuffled.shuffled[26...51])
print("")
print(shuffled.shuffled)
print("")
print(theCardsTopPlayerHas)
print("")
print(theCardsBottomPlayerHas)
}
You are using static var shuffled so you are using static variable. Do you really need a static variable? If not instead of:
struct shuffledVar {
static var shuffled = [String]();
}
use:
var shuffled:[String] = []
and then in code use:
shuffled.append(the_card)
But if you need this variable to be static (for example you are using it in some other view controller) just remove all elements before adding a new one:
//MARK: - Shuffling Cards
shuffledVar.shuffled.removeAll()
You can read more about static vars https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html and more about arrays: https://developer.apple.com/documentation/swift/array

Is there a way for the text in a label to automatically update the display

I'm trying to make an app that lets users input 4 numbers and display what cellular network is that number. Is there a way to automatically display the numbers in the label after the user inputs the numbers without clicking a button? I actually have a code that lets the user input the number but the user must click the enter button for it to display the result on the label. Is there a way for it to automatically display the result? By the way, I'm actually new to swift so I apologize. Here is the code:
import UIKit
import Firebase
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
#IBOutlet weak var numField: UITextField!
#IBOutlet weak var answerField: UILabel!
#IBAction func enterButton(sender: AnyObject) {
matchNumber()
}
func matchNumber(){
let number: String = numField.text!
let numRef = Firebase(url: "https://npi2.firebaseio.com/num_details")
numRef.queryOrderedByKey().observeEventType(.ChildAdded, withBlock: { snapshot in
let network = snapshot.value as! String!
if snapshot.key == self.numField.text! {
self.answerField.text = network
}
else {
self.answerField.text = "Missing"
}
})
}
Add a target to your numField, something like this...
override func viewDidLoad() {
super.viewDidLoad()
self.numField.addTarget(self, action: "editingChanged:", forControlEvents: .EditingChanged)
}
This will trigger the editingChanged method every time a character changes in the numField.
func editingChanged(textField:UITextField) {
if let text = textField.text {
if text.characters.count == 4 {
matchNumber()
}
}
}
Finally we check if there is a string in the input and if it is 4 characters long before running the matchNumber method.
You could use the didSet method.
var numberstring = String() {
didSet {
yourlabel.text = numberstring
}
}
If you are using textfield to take input then you can use textfieldDidEndEditing delegate method.

Count point when a specific button taped parse

Count point in a specific moment when button taped in a new column Parse for example :
#IBAction func nbTapped(sender: AnyObject) {
let PFUser.currentUser()!.objectForKey("buttonpressed") as? Int (buttonpressed)! + 1
}
Should be written as follows:
#IBAction func nbTapped(sender: AnyObject) {
var count = PFUser.currentUser()!.objectForKey("buttonpressed")
PFUser.currentUser()!["buttonpressed"] = count + 1
}
I'm not exactly Swift literate (Obj-C user), but that should work with minimal changes.

Getting types from instance of a class in Swift

I have two files which I am working on for my SpriteKit game: SPSwipes.swift and GameScene.swift.
In my SPSwipes.swift file, inside an SPSwipes class, a variable is triggered by an IBAction.
class SPSwipes: UIViewController {
#IBAction func fiveSwipes(sender: AnyObject) {
var no_of_swipes = 5
}
}
In my GameScene.swift file, an if statement checks what value has been assigned to my variable, and creates an array thereof:
if no_of_swipes == 5 {
var array = Array<UInt32>(count: 5, repeatedValue: 0)
for i in 0 ..< 5 {
array[i] = arc4random_uniform(100)
}
}
I receive this error message:
To 'fix' the problem, I realised that I needed to create an instance of my SPSwipes class, so I added this to my GameScene.swift file:
var swipes = SPSwipes()
And then I changed the if statement to say:
if swipes.no_of_swipes == 5{
...
}
Then I received this error:
As far as I'm aware, I have created an instance of the class correctly, but there is evidently an issue.
Your error is here:
#IBAction func fiveSwipes(sender: AnyObject) {
var no_of_swipes = 5
}
You have created a variable inside the function, therefore the variable doesn't exist outside of the function.
What you want is to have the variable live for as long as an object of the class lives, therefore you need to create the variable one level higher:
class SPSwipes: UIViewController {
var numberOfSwipes = 0
#IBAction func fiveSwipes(sender: AnyObject) {
numberOfSwipes = 5
}
}

Resources