How do I assign Y to X? - swift

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){
...
}

Related

How to access a text field value and convert to double

I am working on trying to build a tip calculator using swift but am running into a multitude of problems. I have a text box where the user enters in the bill amount and then they can adjust a slider to indicate the percentage that they want to tip. I have managed to get the slider and label associated with it to work where changing the value on the slider changes the label. However, I can't figure out how to get the text field to work. I attempted to create an action for the bill amount text box being changed but no matter what I put in it, it doesn't seem like the code is ever being executed (Whenever I run the code and click in the text box, the keyboard won't go away so maybe this is part of the problem?). All that I need is to be able to access the value in the text box field inside of my action when I click the calculate button but I can't seem to even get the value to show up much less convert it to a double so I can perform calculations on it. I am super new to swift and really want to learn what I am doing wrong. I have tried multiple tutorials and similar questions on here but none of them work. I appreciate all help y'all can give.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtBillAmount: UITextField!
#IBOutlet weak var lblTipPercentage: UILabel!
#IBOutlet weak var sldTipPercentage: UISlider!
#IBOutlet weak var lblTipAmount: UILabel!
#IBOutlet weak var lblTotalAmount: UILabel!
var tipPercentage = 10
var billAmount = ""
#IBAction func valueChanged(sender: AnyObject) {
let currentValue = Int(sldTipPercentage.value)
lblTipPercentage.text = "\(currentValue)%"
tipPercentage = currentValue
}
#IBAction func btnCalculate(sender: AnyObject) {
lblTipAmount.text = "\(billAmount)"
}
#IBAction func txtBillAmountValueChanged(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
//txtBillAmount.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func btnReset(sender: UIButton) {
sldTipPercentage.value = 10
lblTipPercentage.text = "10%"
txtBillAmount.text = ""
lblTipAmount.text = "--"
lblTotalAmount.text = "--"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is a screenshot of how the UI looks
Error that I am getting
[Xcode >= 7 and Swift > 2]
Try like this
#IBAction func btnCalculate(sender: AnyObject) {
if let textValue = txtBillAmount.text {
let billAmnt = Double(textValue)
let tipAmount = (billAmnt*tipPercentage)/100
lblTipAmount.text = "\(tipAmount)"
}
}
If you are using Xcode-6 and Swift < 2 then try the following way. because String initializer for Double is only available in Swift 2 (Xcode 7). [Recommend update your Xcode]
#IBAction func btnCalculate(sender: AnyObject) {
let billAmnt = (txtBillAmount.text! as NSString).doubleValue
let tipAmount = (billAmnt*tipPercentage)/100
lblTipAmount.text = "\(tipAmount)"
}

How do I check if x is in a variable in classes within a list?

I have a list called mainframe which holds classes. I want to check before adding a new username; if newusername is in mainframe.usernames perform adding the new username in.
pretty much something like this:
import UIKit
class addNewPassword: UIViewController {
var homeVC = Home()
#IBOutlet weak var createHolderItem: UITextField!
#IBOutlet weak var createHolderUsername: UITextField!
#IBOutlet weak var createHolderPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func savePasswordButton(_ sender: Any) {
let holder = Holder()
holder.item = createHolderItem.text!
holder.username = createHolderUsername.text!
holder.password = createHolderPassword.text!
}
if mainframe.contains(where: { $0.username == holder.username }) {
print("test")
}
else {
homeVC.mainframe.append(holder)
homeVC.tableView.reloadData()
navigationController?.popViewController(animated: true)
}
}
I pretty much want to run a loop, within an if statement. Or am I approaching it the wrong way?
I'm new to programming, did online tutorials and trying to write my first iOS app for my aunt.
if mainframe.usernames.contains(holder.username) {
...
Use contains :
if mainframe.usernames.contains(holder.username) {
...
}

Reuse a value from NSSlider in variable

I have a little problem but I can't figured out ...
I code a sort a Shutdown countdown and I need to re-use the variable name "x" in the following code :
#IBAction func valueChange(sender: NSSlider) {
let x = sender.intValue
valueofSlider.stringValue = "\(x)"
}
IBOutlet weak var countDown: NSTextField!
var starter = false;
#IBAction func startCountDown(sender: NSButton) {
starter = true
}
var trigger = 600 //here I put the value myself but i would like
var trigger = (x * 60) //to get the slider value in seconds
First create an Outlet for your slider and then a variable to hold its value. Assign the variable inside valueChanged and now you can use it wherever you want:
#IBOutlet var slider: UISlider!
var sliderValue: Float = 0
#IBAction func valueChanged(sender: AnyObject) {
sliderValue = slider.value
print(sliderValue)
}

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

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)
}
}

Swift: label text --> "fatal error: unexpectedly found nil while unwrapping an Optional value"

like it says in the title, i am trying to change label text upon click of a button. Error appears at line self.playerChoice.text = "You: Rock"
import UIKit
class ViewController: UIViewController {
var player : Int = Int()
#IBOutlet weak var readyLabel: UILabel!
#IBAction func noButton(sender: AnyObject) {
exit(0)
}
// ---------------------------------------------------------
#IBOutlet var computerChoice: UILabel!
#IBOutlet var playerChoice: UILabel!
#IBOutlet var score: UILabel!
// Variables -------------------------------------------------
let Rock : String = "Rock"
let Paper : String = "Paper"
let Scissors : String = "Scissors"
//------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// ----------------------------------------------------------------
#IBAction func rockButton(rockbut: UIButton) {
player = 0
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Rock"
}
#IBAction func paperButton(paperbut: UIButton) {
player = 1
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Paper"
}
#IBAction func scissorsButton(scissorsbut: UIButton) {
player = 2
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Scissors"
}
}
I ran into this problem and it turned out that the labels that I was trying to edit didn't exist at the time the code ran.
Turns out I was referencing the same view controller from a parent view and a child container view. The labels I was trying to change were only in the container view but as both views loaded it ran the view controller for both so it tried to find the labels that didn't exist in the parent view and threw the above error.
So the lesson I learned... If a reference to a view object is throwing a NIL..
The View isn't properly mapped to the View Controller.
The object within the view isn't mapped to the referencing IBOutlet.
Or as in my case, there are multiple views connected to the same View Controller and references to view objects in one view are not being found in the other.
Looks like player choice is not initialized.
#IBOutlet var playerChoice: UILabel!
Maybe the connection between the outlet and InterfaceBuilder/Storyboard is lost. Try to connect it again.
I've created a small demo and everything works fine:
Check if the circles at the left side of your IBOutlet are filled. Otherwise the connection is lost.
What fixed this for me (and it gets me everytime, especially when you are new to using storyboards) is to make sure that you are initializing your view controller like so :
slideShowVC = (UIStoryboard(name: "Main",bundle: nil).instantiateViewControllerWithIdentifier("WWPhotoSlideShowVC") as! WWPhotoSlideShowVC)
instead of the stand alone xib way :
slideShowVC = WWSlideShowVC()
Or else all your outlets will be nil na many headaches will soon follow.
I ran into the same issue in Xcode 6.2.
I use individual XIBs instead of storyboards. The problem for me was that with Swift, Xcode does not automatically associate the XIB with the view controller if the names are the same. Hence the IBOutlets for the labels are pointing to nil giving the fatal.
You can change the viewcontroller.xib to be called modulename.viewcontroller.xib so that xcode can associate it with the view controller and the issue goes away.
More options are mentioned on this thread:
Can't Load UIViewController XIB file in Storyboard in Swift
I have tried this code and it working fine for me:
class ViewController: UIViewController {
var player : Int = Int() //Declare this globally
#IBOutlet weak var readyLabel: UILabel!
#IBAction func noButton(sender: AnyObject) {
exit(0)
}
// ---------------------------------------------------------
#IBOutlet var computerChoice: UILabel!
#IBOutlet var playerChoice: UILabel!
#IBOutlet var score: UILabel!
// Variables -------------------------------------------------
let Rock : String = "Rock"
let Paper : String = "Paper"
let Scissors : String = "Scissors"
//------------------------------------------------------------
#IBAction func rockButton(rockbut: UIButton) {
player = 0
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Rock"
}
#IBAction func paperButton(sender: UIButton) {
player = 1
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Paper"
}
#IBAction func scissorsButton(sender: UIButton) {
player = 2
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Scissors"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var p : String = "Undecided"
if (player == 0) {
var p: String = "Rock"
} else if (player == 1) {
var p: String = "Paper"
} else if (player == 2) {
var p: String = "Scissors"
}
}
}