Setting UILabel Text to a Variable Not Outputting Correctly - arrays

I am trying to create a quick test system to make an array and display it. Text is inputted into the text field, and when the button is pressed, the text is added to the array, and the output text is updated. However, if I want to add the data "Sandwich" to the array, it outputs in the label as 'Optional("Sandwich")'. I have already tried using the ? and ! to get it out, but nothing seems to work. Would anyone know how to fix this?
#IBOutlet weak var dataEntryTextField: UITextField!
#IBOutlet weak var addDataButton: UIButton!
#IBOutlet weak var addDataLabel: UILabel!
#IBOutlet weak var dataOutput: UILabel!
var List = [""]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.dataEntryTextField.text = ""
self.dataOutput.text = ""
dataOutput.sizeToFit()
//Add more attributes here
//Apply to the label
dataOutput.backgroundColor = UIColor.grayColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(TextField: UITextField) -> Bool
{
dataEntryTextField.resignFirstResponder()
return true;
}
#IBAction func addData(sender: UIButton) {
if self.dataEntryTextField.text == "" {}
else {
if List == [""] {List[0] = "• \(self.dataEntryTextField.text)"}
else {List.append("• \(self.dataEntryTextField.text)")}
self.dataOutput.text = List.joinWithSeparator(" ")
}
self.dataEntryTextField.text = ""
dataEntryTextField.resignFirstResponder()
}

You will have to use optional binding to unwrap your optional value. Assume you have an optional text,
var text: String? = "Sandwich"
print("\(text)") // This would print "Optional("Sandwich")"
When its unwrapped using optional binding, you will get the actual text provided the value is not nil.
if let unwrappedText = text {
print("\(unwrappedText)") // This will print "Sandwich"
}
Refer to this link to understand Optionals.
In your code, you will have to unwrap your self.dataEntryTextField.text value and append it to list.

Related

Why does the console print out the Name of my App/Module?

im currently building an app where you can choose a time and save this data. I built a struct with called Session with this time as an property. When the user save the data i want this new session to be appended to an array of sessions. However when i print out the array there is always the name of my XCode project in front of the struct inside they array, kind of like a path. Do you know how i can fix this, or how i can remove the module name in front of the initialized struct ?
Heres a picture of my console:
Heres my code:
struct Session {
let chosenTime: Int
}
class FirstViewController: UIViewController {
#IBOutlet weak var fiveMinButton: UIButton!
#IBOutlet weak var tenMinButton: UIButton!
#IBOutlet weak var saveDataButton: UIButton!
var sessions: [Session] = []
var selectedTime: Int = 0
#IBAction func timeButtonPressed(_ sender: UIButton) {
selectedTime = sender.tag
print(selectedTime)
}
#IBAction func saveDataPressed(_ sender: UIButton) {
let newSession = Session(chosenTime: selectedTime)
sessions.append(newSession)
print(sessions)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}

Swift - User Defaults not loading array of strings when app is launched

So I have an app for a Midwestern car game where you count cows when you're driving and when you see a cemetery you lose half your cows. Whenever someone sees a cemetery, I have an emoji appear as an appended array of string, so they keep adding up. My problem is I can save the array to user defaults and it will print it correctly, but whenever I relaunch the app, the array goes back to a blank array of strings. So I know the data is saved correctly, just not loading when the app launches.
class ViewController: UIViewController {
#IBOutlet weak var playerOneNameText: UITextField!
#IBOutlet weak var numberOfCowsPlayerOne: UILabel!
#IBOutlet weak var playerOneCows: UILabel!
#IBOutlet weak var playerOneCemeteries: UILabel!
let userDefaults = UserDefaults.standard
var cemeteryEmoji: [String] = UserDefaults.standard.object(forKey: "CemeteryEmoji")! as? [String] ?? []
It will also strangely load the correct array in the field for display, but will start over any time a new cemetery is added:
override func viewDidLoad() {
super.viewDidLoad()
if userDefaults.value(forKey: "CemeteryEmoji") != nil{
playerOneCemeteries.text = "\(UserDefaults.standard.object(forKey: "CemeteryEmoji")!)"
print(cemeteryEmoji)
}else {
playerOneCemeteries.text = ""
}
}
And here's the function for all the cemetery data:
#IBAction func playerOneCemetery(_ sender: UIButton) {
let cemeteryCows = UserDefaults.standard.integer(forKey: "TotalCows") / 2
self.userDefaults.set(cemeteryCows, forKey: "TotalCows")
print(cemeteryCows)
self.numberOfCowsPlayerOne.text = "\(self.userDefaults.string(forKey: "TotalCows")!) cows"
addCemeteryEmoji()
print(UserDefaults.standard.object(forKey: "CemeteryEmoji")!)
func addCemeteryEmoji() {
cemeteryEmoji.append("🪦")
print(cemeteryEmoji)
self.playerOneCemeteries.text = "\(cemeteryEmoji.joined())"
userDefaults.set(cemeteryEmoji.joined(), forKey: "CemeteryEmoji")
}
}
So I'm not sure if it's an issue simply when the app loads or if I need to save it a different way (although as I said, that works perfectly fine with all the print statements). Any help would be great.
The error occurs because you join the array right before saving it which creates a single string.
And when you relaunch the app object(forKey: "CemeteryEmoji")! as? [String] fails.
I highly recommend to name the array more meaningful and use the dedicated API array(forKey:).
Name the array in plural form and declare an empty array
var cemeteryEmojis = [String]()
In viewDidLoad load the array from UserDefaults
override func viewDidLoad() {
super.viewDidLoad()
if let emojis = userDefaults.array(forKey: "CemeteryEmoji") as? [String] {
playerOneCemeteries.text = "\(emojis.joined())"
cemeteryEmojis = emojis
print(cemeteryEmojis)
} else {
playerOneCemeteries.text = ""
}
}
And delete joined() in the set line of addCemeteryEmoji
func addCemeteryEmoji() {
cemeteryEmojis.append("🪦")
print(cemeteryEmojis)
self.playerOneCemeteries.text = "\(cemeteryEmojis.joined())"
userDefaults.set(cemeteryEmojis, forKey: "CemeteryEmoji")
}

Random data transfer to button in Swift. (Array)

import UIKit
class ViewController: UIViewController {
var buttonArray = [String] ()
#IBOutlet weak var button3: UIButton!
#IBOutlet weak var button2: UIButton!
#IBOutlet weak var button1: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
buttonArray.append("answer1")
buttonArray.append("answer2")
buttonArray.append("answer3")
}
#IBAction func buttonClick(_ sender: UIButton) {
while true {
let randomArray = buttonArray[Int.random(in: 0...2)]
button1.titleLabel?.text = randomArray
break
}
}
}
I want to create a test. This test will have 3 answer choices and these answers will be randomly assigned to the buttons. I don't want an answer to be assigned to two choices. for this, I want to take the first assigned option into the array and remove it from the array after it is assigned. i don't understand how i can do this
You can remove an item at a random index. This item is returned from remove(at:
let randomElement = buttonArray.remove(at: Int.random(in: 0..<buttonArray.count)]
button1.titleLabel?.text = randomElement
Side note: Never hard-code array indices for a range.
To assign all three values randomly to the three buttons shuffle the array
let shuffledArray = buttonArray.shuffled()
button1.titleLabel?.text = shuffledArray[0]
button2.titleLabel?.text = shuffledArray[1]
button3.titleLabel?.text = shuffledArray[2]

Showing array content on a button, using a label

I have searched around but have not found an answer. It may be simple but I can nor figure out how you are suposed to do it. So...
I want a button to show an array on a label. When I press the first time, the label show the first number in the array, an pressing a second time makes the label print the second number in the array.
var primeString = ["60","52","81","61","85"]
#IBOutlet var PrimeLabel: UILabel!
#IBAction func NewAction(sender: AnyObject) {
// Here is where I want to make the label show the array in the order when I press it.
}
Declare a variable count and initialise to 0
var primeString = ["60","52","81","61","85"]
var count = 0
#IBOutlet var PrimeLabel: UILabel!
And then action for Button Click.
#IBAction func NewAction(sender: AnyObject) {
PrimeLabel.text = primeString[count%primeString.count]
count++
}
So just to get this straight. Each time you press the button you want to display the next element in the array through the label. Okay, that should be fairly simple. Something like below will do that for you.
var primeString = ["60","52","81","61","85"]
var currentElement = 0
#IBOutlet var PrimeLabel: UILabel!
#IBAction func NewAction(sender: AnyObject) {
if currentElement < primeString.count {
PrimeLabel.text = primeString[currentElement]
currentElement++
} else {
print("No more elements to display.")
}
}
No need to have the view did load, as we don't need to do any setup once the view has loaded. I hope this helps you out.
Why don't you use Generator for this?
E.g. something like:
var primeStringGenerator = ["60","52","81","61","85"].generate()
#IBOutlet var PrimeLabel: UILabel!
#IBAction func NewAction(sender: AnyObject) {
PrimeLabel.text = primeGenerator.next() ?? "n/a"
}
var primeString = ["60","52","81","61","85"]
#IBOutlet var PrimeLabel: UILabel!
var number = 0
#IBAction func NewAction(sender: AnyObject) {
PrimeLabel.text = primeString[i]
i++
}

How to set a NSUserDefault to the last index in an array the user pressed (swift)

I am trying to make an app that will display a array of items which the user clicks a button to go through. When the user exits the app I would like the app to save the in the last thing the user pressed. So far I have tried to set NSUserDefaults but I have been unsuccessful thus far.
Code in Swift
#IBOutlet weak var TechByteLabel: UILabel!
let defaults = NSUserDefaults.standardUserDefaults()
var TechfactIndex = 0
let TechnologyfactBook = TechFactBook()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
TechByteLabel.text = TechnologyfactBook.TechfactsArray[TechfactIndex]
defaults.setObject(TechfactIndex, forKey: "ByteLocation")
NSUserDefaults.standardUserDefaults().synchronize()
}
#IBAction func showFunFact() {
TechfactIndex++
if (TechfactIndex >= TechnologyfactBook.TechfactsArray.count) {
self.TechfactIndex = 0
}
TechByteLabel.text = TechnologyfactBook.TechfactsArray[TechfactIndex]
}
I would give you the same advice I gave this guy in this answer here: https://stackoverflow.com/a/31351805/3149796
If you want to save the last value from the "TechfactsArray", then you can do it via using the property:
defaults.setObject(TechfactsArray.last, forKey: "LastValue")
NSUserDefaults.standardUserDefaults().synchronize()
Hope that code below will helps!
override func viewDidLoad() {
super.viewDidLoad()
// Load your settings from NSUserDefault
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
// Save new settings to NSUserDefault
}
Read the defaults value in viewDidLoad and set it in showFunFact().
The functions to do that would be:
// viewDidLoad:
TechfactIndex = NSUserDefaults.standardUserDefaults().integerForKey("ByteLocation")
// showFunFact
NSUserDefaults.standardUserDefaults().setInteger(TechfactIndex, forKey: "ByteLocation")

Resources