I have two Random numbers generating in ViewDidLoad. I Want to plus these two numbers and the result should be checked in a button with data of a input field. my problem is that I do not know how to transfer result to the function CheckResultBtn . now it does not recognise result.
here is My codes and I really appreciate any kinds of help
class ViewController: UIViewController {
#IBOutlet weak var lblRandomNumOne: UILabel!
#IBOutlet weak var lblRandomNumTwo: UILabel!
#IBOutlet weak var KidsField: UITextField!
#IBOutlet weak var Showresult: UILabel!
#IBOutlet weak var CheckResult: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let x = Int.random(in: 0 ..< 10)
lblRandomNumOne.text = String(x);
let y = Int.random(in: 0 ..< 10)
lblRandomNumTwo.text = String(y);
let result = x + y;
CheckResultBtn(result) //not sure about this
}
#IBAction func CheckResultBtn(_ sender: Any)
{
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
}
declare the variable "result" before the viewDidload function
var result : Int!
then proceed to perform the operation on the variable in your viewDidload and you can get rid of this line
CheckResultBtn(result)
and you should be able to access the result variable in your IBAction function
You can try
#IBAction func checkResultBtn(_ sender: Any) {
displayRes(Int(kidsField.text!)!)
}
func displayRes(_ result:Int) {
showresult.text = result == kidsresult ? "Bravo" : "Try Again!"
}
Then inside viewDidLoad
displayRes(x+y)
create a new function instead of using action Method
like this :
func CheckResultBtn(_ result : Int) {
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
or create a variable
var result : Int?
assign a value
result = x + y;
and use inside the action Method
var result : Int?
override func viewDidLoad() {
super.viewDidLoad()
let x = Int.random(in: 0 ..< 10)
lblRandomNumOne.text = String(x);
let y = Int.random(in: 0 ..< 10)
lblRandomNumTwo.text = String(y);
result = x + y;
}
#IBAction func CheckResultBtn(_ sender: Any) {
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
Related
Very basic code
I am doing coding at school and have to create an app. Part of the app is a water usage calculator. Even though I am checking for nil values from the optional, it gets the error: "Fatal Error: Unexpectedly found nil while unwrapping an optional". It finds this error during a random part of func btnCalculate.
import UIKit
class WaterCalcViewController: UIViewController {
//Inputs
#IBOutlet weak var txtShowers: UITextField!
#IBOutlet weak var txtBaths: UITextField!
#IBOutlet weak var txtDishwasher: UITextField!
#IBOutlet weak var txtWashingMachine: UITextField!
#IBOutlet weak var txtTeeth: UITextField!
#IBOutlet weak var txtToilet: UITextField!
#IBOutlet weak var txtNumOfPeople: UITextField!
//Inputs for the user to add values to their respective use of each item/thing
//Outputs
#IBOutlet weak var lblShowerError: UILabel!
#IBOutlet weak var lblBathError: UILabel!
#IBOutlet weak var lblDishwasherError: UILabel!
#IBOutlet weak var lblWashingMachineError: UILabel!
#IBOutlet weak var lblTeethError: UILabel!
#IBOutlet weak var lblToiletError: UILabel!
#IBOutlet weak var lblNumOfPeopleError: UILabel!
#IBOutlet weak var lblTotalSum: UILabel!
//Labels that appear when no value is given for their respective text field
//Functions
//Actions
#IBAction func btnBack(_ sender: Any) {
let destinationVC = self.storyboard?.instantiateViewController(identifier: "tabController") as! UITabBarController
destinationVC.selectedIndex = 3
destinationVC.modalPresentationStyle = .fullScreen
self.present(destinationVC, animated: true, completion: nil)
}
var success: Int = 0
#IBAction func btnCalculate(_ sender: Any) {
success = 0
let shower: Int? = Int(txtShowers.text!)
if shower != nil {
success = success + 1
} else if shower == nil {
lblShowerError.text = ("Please input a valid number")
}
let bath: Int? = Int(txtShowers.text!)
if bath != nil {
success = success + 1
} else if bath == nil {
lblBathError.text = ("Please input a valid number")
}
let dishwasher: Int? = Int(txtShowers.text!)
if dishwasher != nil {
success = success + 1
} else if dishwasher == nil {
lblDishwasherError.text = ("Please input a valid number")
}
let washingMachine: Int? = Int(txtShowers.text!)
if washingMachine != nil {
success = success + 1
} else if washingMachine == nil {
lblWashingMachineError.text = ("Please input a valid number")
}
let teethLength: Int? = Int(txtShowers.text!)
if teethLength != nil {
success = success + 1
} else if teethLength == nil {
lblTeethError.text = ("Please input a valid number")
}
let toiletFlushes: Int? = Int(txtShowers.text!)
if toiletFlushes != nil {
success = success + 1
} else if toiletFlushes == nil {
lblToiletError.text = ("Please input a valid number")
}
let numOfPeople: Int? = Int(txtShowers.text!)
if numOfPeople != nil {
success = success + 1
} else if numOfPeople == nil {
lblNumOfPeopleError.text = ("Please input a valid number")
}
if success == 7 {
var totalSum = (shower! * 10)
totalSum = totalSum + (bath! * 150)
totalSum = totalSum + (dishwasher! * 30)
totalSum = totalSum + (washingMachine! * 90)
totalSum = totalSum + (teethLength! * 5)
totalSum = totalSum + (numOfPeople! * 10)
totalSum = totalSum + (toiletFlushes! * Int(4.5))
lblTotalSum.text = ("Your average daily water use is \(totalSum)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
#objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
The issue can be you are trying to convert a nil value into Int.
Here in every this kind of line :- let shower: Int? = Int(txtShowers.text!) here txtShowers.text can be a nil or any other similar value try having a break point at this.
You can try this instead first get all the values which you want using guard let like this :-
guard let shower = txtShowers.text else {\\Show some error or what you want}
This will also reduce your number or lines of code.
and then you can perform the operations on shower easily.
Just for the info :- you should never use forcecast in your code always try to go with guard let or if let
Heres the code I have so far, now when a user inputs any letter, my label display nothing, what I would like to figure out is how to turn that nothing "", into a 0. I tried doing an if statement on my "label.txt ="'s but that didn't pan out. What would be a better way of finding my desired results?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var game1: UITextField!
#IBOutlet weak var game2: UITextField!
#IBOutlet weak var game3: UITextField!
#IBOutlet weak var series: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var high: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculate(_ sender: Any) {
self.view.endEditing(true)
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
let gameResultsArray = [game1Results, game2Results, game3Results]
let sumArray = gameResultsArray.reduce(0, +)
let positiveArray = gameResultsArray.filter {
(item: Int) -> Bool in return item > 0
}
var avgArrayValue = 0
if positiveArray.count == 0
{
avgArrayValue = 0
}else {
avgArrayValue = sumArray / positiveArray.count
}
series.text = "\(sumArray)"
average.text = "\(avgArrayValue)"
if let maximumVal = gameResultsArray.max() {
high.text = String(maximumVal)
}
}
}
Here is what you need, convert String to Int and give the default 0. Instead of using the guard let return use this method:
Instead of this:
guard let game1Results = Int(text1) else { return }
Use this:
let game1Results = Int(text1) ?? 0
This is my code I don't know what I did wrong. All of the problems are in function steve. LebelText is a timer timer label that is segued from another view controller. So i want to take lebetText convert it to a int to subtract 1 from it then reconvert it back to a string to display the number.
This is view Controller a. The texted being segued is lebelText.
import UIKit
class testViewController: UIViewController {
#IBOutlet var lazel: UILabel!
#IBOutlet var plax: UIButton!
#IBOutlet var stopx: UIButton!
var timer = Timer()
var counter = 0.0
var isRunning = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let DestViewController : restultViewController = segue.destination as! restultViewController
DestViewController.LebelText = lazel.text!
}
#IBAction func play(_ sender: Any) {
if !isRunning{
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(testViewController.update), userInfo: nil, repeats: true)
}
plax.isEnabled = false
stopx.isEnabled = true
}
#IBAction func stop(_ sender: Any) {
plax.isEnabled = true
stopx.isEnabled = false
timer.invalidate()
isRunning = false
}
func update(){
counter += 0.1
lazel.text = String(format: "1%f", counter)
lazel.text = "\(counter)"
}}
this is view controller b. The goal is to go to take lebelText convert it to a int to subtracted 1 from it. Then convert it back to a string so it can be displayed.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var dxe: UILabel!
var LebelText = String()
let myInt = Int()
override func viewDidLoad() {
super.viewDidLoad()
steve()
}
func steve(){
var eq = LebelText
var intValue = Int(eq)
let vx = intValue! - 1
let ramit = String(vx)
dxe.text = ramit
}
ok so to get rid of the optional and to be sure it all works you should do like
if let intValue = Int(eq) {
vx = intValue - 1
dxe.text = String(vx)
} else {
//do some stuff if you cannot convert eq to Int
}
but I would recommend you to start with some easier tasks, it looks like you did not completely learn basics.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var someLabel: UILabel!
public var myText: String?
override func viewDidLoad() {
super.viewDidLoad()
self.parseData()
}
private func parseData(){
guard let unwrapedText = self.myText else {
//you didn't pass string
return
}
if let myInt = Int(unwrapedText) {
myInt = myInt - 1
self.someLabel.text = String(myInt)
} else {
//you string is not convertable to int
}
}
}
You Can just do this.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var dxe: UILabel!
var LebelText = String()
let myInt = Int()
override func viewDidLoad() {
super.viewDidLoad()
steve()
}
func steve(){
var eq = Int(LebelText.text)
eq = eq - 1
dxe.text = String(eq)
}
I want to add value of textfield. I want to check textfield is empty or not or checking other value than int. I am newer in Swift. Please help any help would be apperciated.
#IBOutlet var label :UILabel!
#IBOutlet var first : UITextField!
#IBOutlet var third : UITextField!
#IBOutlet var second : UITextField!
var bloa :NSString?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func playPressed(sender: UIButton) {
var a: Int = 0
var b: Int = 0
var c: Int = 0
var d: Int = 0
if first.text!.isEmpty || second.text!.isEmpty || third.text!.isEmpty {
return
}
else
{
// If on first textfield there is another value than int they show
//fatal error: unexpectedly found nil while unwrapping an Optional value
a = (Int)(first.text!)!
b = Int(second.text!)!
c = Int(third.text!)!
d = a + b + c
label?.text = String (format: "%d",d)
}
Try this:
if first!.text == "" || second!.text == "" || third!.text == "" {
}
You don't need to check if it is empty or not this way:
guard let a = Int((first?.text)!), b = Int((second?.text)!) , c = Int((third?.text)!) else {
print("Not convertable to Int or field are empty")
return
}
And your final code will be:
import UIKit
class ViewController: UIViewController {
#IBOutlet var label :UILabel?
#IBOutlet var first : UITextField?
#IBOutlet var third : UITextField?
#IBOutlet var second : UITextField?
override func viewDidLoad() {
playBackgroundMusic("Naughty_Boy.mp3")
}
#IBAction func playPressed(sender: UIButton) {
guard let a = Int((first?.text)!), b = Int((second?.text)!) , c = Int((third?.text)!) else {
print("Not convertable to Int or field are empty")
return
}
let d = a + b + c
label?.text = String (format: "%d",d)
}
}
If you set the keyboard for all these text boxes as below screenshot and change is marked in red rectangle. You don't need to check the given character/word is integer or not in the code.
Set your keyboard type to Number Pad from the Storyboard. then do this in code:
#IBAction func playPressed(sender: UIButton) {
if first?.text?.isEmpty || second?.text?.isEmpty || third?.text?.isEmpty {
}
}
I am a newbie swift programmer, and I have been asked to write an app that allows you to type in a word, and then generates a random Haiku
This is a tabbed application, with two ViewControllers.
(poem) based on that word. So in the FirstViewController I have the data, and I want to display that data in a nice way, in the SecondViewController.
I have all the poem lines and all in the FirstViewController, but I would like to access these variables in the SecondViewController. I have tried creating a function, that does nothing but returning them, and then in the SecondViewController calling that function, but without any result, since the function simply returned nil. Would be pleased if any of you could help
Thank you!
Here is the FirstViewController:
import UIKit
import Foundation
class FirstViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var keyWordTextField: UITextField!
#IBOutlet weak var syllableSlider: UISlider!
#IBOutlet weak var syllableSliderLabel: UILabel!
var syllableSliderValue = 1
#IBOutlet weak var lineOneTextField: UITextField!
#IBOutlet weak var lineTwoTextField: UITextField!
#IBOutlet weak var lineThreeTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
lineOneTextField.text = "Rad 1"
lineTwoTextField.text = "Rad 2"
lineThreeTextField.text = "Rad 3"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func syllableValueChanged(sender: UISlider) {
syllableSliderValue = Int((sender.value))
syllableSliderLabel.text = "Ordet har: \(syllableSliderValue) stavelser"
}
#IBAction func getNewHaiku() {
if keyWordTextField.text != "" {
let keyWord = keyWordTextField.text
let lineOne = generateLine(keyWord: keyWord, syllables: syllableSliderValue, lineSyllableLenght: 5)
let lineTwo = generateLine(keyWord: keyWord, syllables: syllableSliderValue, lineSyllableLenght: 7)
let lineThree = generateLine(keyWord: keyWord, syllables: syllableSliderValue, lineSyllableLenght: 5)
lineOneTextField.text! = lineOne
lineTwoTextField.text! = lineTwo
lineThreeTextField.text! = lineThree
}
}
func generateLine(#keyWord: String, syllables : Int, lineSyllableLenght : Int) -> String {
let oneSyllables = Dict().oneSyllables
let twoSyllables = Dict().twoSyllables
let threeSyllables = Dict().threeSyllables
let fourSyllables = Dict().fourSyllables
let randomOneSyllableWordNumber = Int(arc4random_uniform(UInt32(oneSyllables.count)))
let randomTwoSyllableWordNumber = Int(arc4random_uniform(UInt32(twoSyllables.count)))
let randomThreeSyllableWordNumber = Int(arc4random_uniform(UInt32(threeSyllables.count)))
let randomFourSyllableWordNumber = Int(arc4random_uniform(UInt32(fourSyllables.count)))
var lineArray : [String] = []
var line = ""
lineArray.append(keyWord)
if syllables == 1 {
let randomWordMethod = Int(arc4random_uniform(2))
if randomWordMethod == 0 {
lineArray.append(fourSyllables[randomFourSyllableWordNumber])
} else if randomWordMethod == 1 {
lineArray.append(threeSyllables[randomThreeSyllableWordNumber])
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
} else if randomWordMethod == 2 {
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
lineArray.append(twoSyllables[randomOneSyllableWordNumber])
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
}
} else if syllables == 2 {
let randomWordMethod = Int(arc4random_uniform(2))
if randomWordMethod == 0 {
lineArray.append(twoSyllables[randomOneSyllableWordNumber])
lineArray.append(oneSyllables[randomTwoSyllableWordNumber])
} else if randomWordMethod == 1 {
lineArray.append(threeSyllables[randomThreeSyllableWordNumber])
} else if randomWordMethod == 2 {
lineArray.append(twoSyllables[randomTwoSyllableWordNumber])
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
}
} else if syllables == 3 {
let randomWordMethod = Int(arc4random_uniform(1))
if randomWordMethod == 0 {
lineArray.append(twoSyllables[randomTwoSyllableWordNumber])
} else if randomWordMethod == 1 {
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
}
} else if syllables == 4 {
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
}
if lineSyllableLenght == 7 {
let randomWordMethod = Int(arc4random_uniform(1))
if randomWordMethod == 0 {
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
lineArray.append(oneSyllables[randomOneSyllableWordNumber])
} else if randomWordMethod == 1 {
lineArray.append(twoSyllables[randomTwoSyllableWordNumber])
}
}
for word in lineArray {
line += " \(word)"
}
line += ","
return line
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func getData() -> (line2: String, line3: String) {
return (lineTwoTextField.text, lineThreeTextField.text)
}
}
Ps, the "Dict" is another file, but only containing words.
The second view controller is just blank.
Or you could make it a global variable so any file can access it.
struct structname {
static var yourvariable = value
}
When calling it, you enter
filename.structname.yourvariable
You need to pass the instances like this in second view controller:
var firstViewController: FirstViewController?
Then in the master instance which knows both:
secondViewController.firstViewController = firstViewController
(e.g. in awakeFromNib) assuming that they are known in the master instance like
let firstViewController = FirstViewController()
let secondViewController = SecondViewController()
Finally in SecondViewController you can access the first:
firstViewController?.generateLine....