In Swift how do I convert int to string and reverse and display result? - swift

The program is suppose to change F TO C and reverse. With the Switch it changes from on to off and on is suppose to be C to f and off is F to c and entering the # underneath in the text field.
When clicking the submit button it takes whats in the text field transfers it to an in preforms the algorithm and then displays it in the textfield.
I believe the conversion is going correctly but will not display the actual result. Or the way its being converted is wrong.
#IBOutlet weak var buttonClicked: UIButton!
#IBOutlet weak var mySwitch: UISwitch!
#IBOutlet weak var myTextField: UITextField!
#IBOutlet weak var User: UITextField!
func stateChanged(switchState: UISwitch) {
if switchState.on {
myTextField.text = "Convert to Celius"
} else {
myTextField.text = "Convert to Farheniet"
}
}
#IBAction func buttonClicked(sender: UIButton) {
if mySwitch.on {
var a:Double? = Double(User.text!)
a = a! * 9.5 + 32
User.text=String(a)
mySwitch.setOn(false, animated:true)
} else {
var a:Double? = Double(User.text!)
a = a! * 9.5 + 32
User.text=String(a)
mySwitch.setOn(true, animated:true)
}
}

I am using an older version of XCode(6.4) so my code will be a little bit different from yours. From what I understand your function buttonClicked should take the argument of AnyObject instend of UIButton. Also you do not call the function stateChanged in your code at all. The following code should help achieve what you trying to do.
#IBOutlet weak var mySwitch: UISwitch!
#IBOutlet weak var myTextField: UITextField!
#IBOutlet weak var User: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// sets the textfield to the intended conversion on load.
if mySwitch.on {
myTextField.text = "Convert to Celius"
}
else {
myTextField.text = "Convert to Farheniet"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// changes the myTextFiled text to the intended conversion when the switch is manually switched on or off
#IBAction func switched(sender: AnyObject) {
if mySwitch.on {
myTextField.text = "Convert to Celsius"
}
else {
myTextField.text = "Convert to Fahrenheit"
}
}
// changes the myTextField text to intended reverse conversion after the buttonClicked func is completed.
func stateChanged(switchState: UISwitch) {
if switchState.on {
myTextField.text = "Convert to Celsius"
}
else {
myTextField.text = "Convert to Fahrenheit"
}
}
// do the intended conversion(old version of XCode 6.4)
#IBAction func buttonClicked(sender: AnyObject) {
if mySwitch.on {
var a = (User.text! as NSString).doubleValue
a = (a-32)*(5/9)
User.text="\(a)"
mySwitch.setOn(false, animated:true)
stateChanged(mySwitch)
}
else {
var a = (User.text! as NSString).doubleValue
a = a * (9/5) + 32
User.text="\(a)"
mySwitch.setOn(true, animated:true)
stateChanged(mySwitch)
}
}

Related

How do I assign Y to X?

I couldn't figure out how to copy value of variable into another variable in Swift, an example code for this in python would be
def assignVariable():
x=1
y=x
return y
RESULT 1
When I did this it doesn't seem to work in Swift. Is there any solution to this or am I doing something wrong?
Edit: problem is at
var originalCount=countDown
it gave me Use of unresolved identifier 'countDown' but when I assign it literally it works. Here's my swift code
import Cocoa
class MainWindow: NSWindowController {
var hitCount = 0
var started:Bool = false
var timer = 10
var colorList: [NSColor] = [ NSColor.black,NSColor.blue,NSColor.brown,NSColor.cyan,NSColor.darkGray,NSColor.gray,NSColor.green,NSColor.lightGray,NSColor.magenta,NSColor.orange,NSColor.purple,NSColor.red,NSColor.white,NSColor.yellow]
#IBOutlet weak var button1: NSButton!
#IBOutlet weak var scrubber1: NSScrubber!
#IBOutlet weak var display: NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
var countdown=10
var originalCount=countDown
//(countdown,originalCount) = (10,10) //it works if i use this instead
func startGame(){
if(countDown>0 || started==true){
display.stringValue=String(countDown)
countDown-=1
let seconds = 1.0
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
self.startGame()
}
}else{
display.stringValue="Done "+String(hitCount)+" Taps in " + String(originalCount) + "Tap to RESET"
started=false
countDown=10;
}
}
#IBAction func labelPress(_ sender: Any) {
display.stringValue="__RESET__"
hitCount=0
countDown=10
started=false
}
#IBAction func buttonPressed(_ sender: Any) {
if started==false{
startGame()
}
button1.bezelColor = colorList[Int.random(in: 0..<colorList.count)]
started=true
button1.title=String(hitCount)
hitCount+=1
}
}
You can't initialise one variable with another at the top level in your class. Looking at your code I don't think that originalCount needs to be a property, move it inside startGame() instead and make it a local variable and also use let since it isn't changing
var countdown=10
func startGame(){
let originalCount = countDown
if(countDown>0 || started==true){
...
}

Variable error in Swift code

I have an Xcode project which has some error. I had only a problem with a variable. I convert the txt string variable to int and this called txtint. When I want to make an calculation I can't because it has null value what is impossible because I give a value in function "pass" and then when I want to subtract I can't because txtint has null value.
//
// ViewController.swift
// Biophere
//
// Created by Coder on 2017. 10. 22..
// Copyright © 2017. Pliz Help. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var label: UILabel!
#IBOutlet weak var textview: UITextField!
#IBOutlet weak var conv: UILabel!
var text: String? = nil
var txt: String? = nil
var convert: String? = nil
var textint: Int? = nil
var txtint: Int? = nil
#IBAction func pass(_ sender: Any) {
var txt: String {
get {
return textview.text ?? ""
}
set {
textview.text = newValue
}
}
//conv.text = txt
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label.text = text
txt = textview.text
}
#IBAction func saveButton(_ sender: Any) {
let textint = Int(text!)
let txtint = Int(txt!)
convert = String(textint! - txtint!)
conv.text = txt
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ERROR: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
var text: String = ""
var txt: String = ""
var convert: String = ""
var textint: Int = 0
var txtint: Int = 0
#IBAction func saveButton(_ sender: Any) {
if let textint = Int(text), let txtint = Int(txt) {
convert = String(textint - txtint)
conv.text = txt
}else{
print("handle it")
}
}
Suggestion: Try to give variable name descriptive it is a basic thing for development.

Class 'ViewController' has no initializers - Similar questions couldn't resolve issue

I have searched for similar questions, but they could not resolve my issue, so I hope it's ok, that I am asking it again. Here is my code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var revealLabel: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var textField: UITextField!
var userGuess: Int
var heldUpFingers: Int
var score: Int = 0
#IBAction func startGame(sender: UIButton) {
userGuess = Int(textField.text!)!
if textField.text == nil {
revealLabel.text = "Please enter a number from 1 to 5"
} else if userGuess > 5 {
revealLabel.text = "Please enter a number from 1 to 5"
} else {
heldUpFingers = Int(arc4random_uniform(5) + 1)
if heldUpFingers == userGuess {
revealLabel.text = "You guessed right!"
score += 1
scoreLabel.text = String(score)
} else {
revealLabel.text = "Wrong, it was \(heldUpFingers)"
}
}
}
}
It gives me the error "Class 'ViewController' has no initializers" in the 3rd line. Thanks in advance!
It is because userGuess and heldUpFingers aren't assigned yet. You can either make these optional by adding a ? after the Int or by setting a default value to them. So either:
var userGuess: Int?
var heldUpFingers: Int?
You will then need to unwrap them/check there not nil later in your code like this:
if userGuess != nil {
//now safely use userGuess!
}
Or
var userGuess: Int = 0
var heldUpFingers: Int = 0

if statement returning a value not working for UiLabel

my fairly new to swift and programming, I'm trying to display a value from an if statement. Here is my func within my UiLabel. I've tried a few variations along the same lines but it only every returns "calculate.fuelTank" it never seems to trigger the second part to my IF statement?
#IBOutlet weak var startingFuelDisplay: UILabel! //not working yet
func refreshUiopeningFuel() {
if calculate.totalFuel <= Double(calculate.fuelTank) {
print (Double(calculate.fuelTank)) // FuelTank
} else {
print (calculate.totalFuel) // TotalFuel
}
Do I need to add a bool argument to trigger "else"? I have also tried using the "return" function with initialised string which included the value I was trying to extract, finally I need this to work for another display.
here is my full view controller code (i'm new I'm sure it could be cleaner)
import UIKit
class ViewController: UIViewController {
let calculate = Inputs ( raceLaps: 13, fuelRate: 3.7, fuelTank: 110, laptime: 85.456, tyreWear: 0.05 )
#IBOutlet weak var rate: UITextField!
#IBOutlet weak var laps: UITextField!
#IBOutlet weak var tank: UITextField!
#IBOutlet weak var tyreWear: UITextField!
#IBOutlet weak var laptime: UITextField!
#IBOutlet var cancelKeyboard: UITapGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
refreshUiFuel()
refreshUiStops()
refreshUiTyreLife()
refreshUiTyreLifeLaps()
refreshUiopeningFuel()
refreshUiBoxOnLap ()
}
#IBAction func calculate(sender: UIButton) {
if let rateVal = Double(rate.text!),
tankVal = Int(tank.text!),
lapVal = Int(laps.text!),
wearVal = Double(tyreWear.text!),
laptimeVal: Float = 85.456 {
let fuelModel = Inputs(raceLaps: lapVal, fuelRate: rateVal, fuelTank: tankVal, laptime: laptimeVal, tyreWear: wearVal )
totalFuelDisplay.text = ("\(Double(fuelModel.totalFuel))")
totalStopsDisplay.text = ("\(Int(fuelModel.totalStops))")
tyreLifeDisplay.text = ("\(Int(fuelModel.tyreChangesRaceDistanceTotal))")
tyreLifeLapsDisplay.text = ("\(Int(fuelModel.tyreLife))")
startingFuelDisplay.text = ("\(refreshUiopeningFuel())")
}
else {
totalFuelDisplay.text = "missing value"
totalStopsDisplay.text = "missing value"
tyreLifeDisplay.text = "missing value"
tyreLifeLapsDisplay.text = "missing value"
startingFuelDisplay.text = "missing Value"
}
}
#IBOutlet weak var totalFuelDisplay: UILabel!
func refreshUiFuel()->String {
return totalFuelDisplay.text!
}
#IBOutlet weak var totalStopsDisplay: UILabel!
func refreshUiStops()->String {
return totalStopsDisplay.text!
}
#IBOutlet weak var tyreLifeDisplay: UILabel!
func refreshUiTyreLife()->String {
return tyreLifeDisplay.text!
}
#IBOutlet weak var tyreLifeLapsDisplay: UILabel!
func refreshUiTyreLifeLaps()->String {
return tyreLifeLapsDisplay.text!
}
#IBOutlet weak var pitOnLapDisplay: UILabel!
func refreshUiBoxOnLap () {
}
#IBOutlet weak var startingFuelDisplay: UILabel! //not working yet
func refreshUiopeningFuel() ->Double {
print(calculate.fuelTank)
print(calculate.totalFuel)
if calculate.totalFuel <= Double(calculate.fuelTank) {
return Double(calculate.fuelTank) // FuelTank
} else {
return calculate.totalFuel // TotalFuel
}
}
}
all helped welcomed
Judging from the natural real-world logic, it appears you've simply reversed the if/else logic. It would seem that if totalFuel is less than the tank's capacity (the if clause), you should return totalFuel in that case, and return the tank capacity in the else clause.

Swifit (my first program) catching user input

I can't figure out how the value of a.sucess and a.attempt will come from the input of the user writing numbers in the success and attempt box.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Attempts: UITextField!
#IBOutlet weak var Sucess: UITextField!
#IBOutlet weak var Check: UIButton!
#IBOutlet weak var thepage: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Check(sender: UIButton) {
var str = "here"
class Tries {
var Attempts:Float64 = 100.00
var Sucess:Float64 = 50.00
init() {
}
func Shot() {
if Attempts < 99.5 {
print ("you need more attempts :( Shoot some more!!")
}
else if Attempts > 99 && Sucess > 49 && Sucess / Attempts > 0.4999
{
print("accepted")
} else {
print("failed ")
}
}
}
var a = Tries()
a.Attempts = 200 // this input should come from the user writing input in the textfield... (NEED HELP HERE)
a.Sucess = 100 // this input should come from the user writing input in the textfield... (NEED HELP HERE)
a.Shot() // This is the function that should load when you click on the button: click
}
I want a.Attempts and a.Sucess to get the value from the user writing his/Her own numbers in the two boxes.
First of all you have a very bad style of writing code. What you wrote is very difficult to read. Call variables clearer and do not call objects with a capital letter, it need call the names indicate the type and not the names of the objects. Reed this for example: https://github.com/raywenderlich/swift-style-guide to make your code more clear.
About you problem. Maybe I did not quite understand the question, but apparently you just have to read the value of the UITextField object and you can do it like:
let strValue = textField.text // in your case Attempts.text
then you need to convert it to CGFloat:
let floatValue = CGFloat((strValue as NSString).floatValue)
and then you can use it in your object:
a.Attempts = floatValue
You should still check that the conversion went well and only then assign a value.
You can do this for example to solve you problem:
import UIKit
class ValuesChecker {
class func checkValues(firstValue: Float, secondValue: Float) -> String {
if firstValue < 99.5 {
return "you need more attempts :( Shoot some more!!"
} else if firstValue > 99 && secondValue > 49 && secondValue / firstValue > 0.4999 {
return "accepted"
} else {
return "failed "
}
}
}
class ViewController: UIViewController {
#IBOutlet weak var firstTextField: UITextField!
#IBOutlet weak var secondTextField: UITextField!
#IBAction func actionWithPressButton(sender: AnyObject) {
let firstValue = (firstTextField.text as NSString).floatValue
let secondValue = (secondTextField.text as NSString).floatValue
println(ValuesChecker.checkValues(firstValue, secondValue: secondValue))
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Comments:
You dont need to create class object in your case. You can create static class method like checkValues
Instead of a String you can give out test results in any way, and use it later in the program