Swift: Missing Argument Error - swift

Im having an issue here when trying to follow the first stanford lecture. I am assuming it is because I am using swift 2.... which was just recently released. (And the class is not) Below I show where I am getting errors. In the class the "enter" button on the calculator has the code #IBAction func enter() { but in mine it is #IBAction func enter(sender: UIButton) {
Is this something I did wrong when bringing the button into my code? Any ways to fix? Let me know if I can clarify anything.
import UIKit
class ViewController: UIViewController
{
#IBOutlet var display: UILabel!
var userIsInTheMiddleOfTypingANumber: Bool = false
#IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
#IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter() // Here is my error: *Missing Argument for parameter on the line of code that says enter()
}
switch operation {
case "x":
if operandStack.count >= 2 {
displayValue = operandStack.removeLast() * operandStack.removeLast()
enter() // Here is my error: Again...
}
default: break
}
}
var operandStack = Array<Double>()
#IBAction func enter(sender: UIButton) {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
}

enter requires an input parameter but you didn't supply it with any. Replace it with enter(sender)
#IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter(sender)
}
switch operation {
case "x":
if operandStack.count >= 2 {
displayValue = operandStack.removeLast() * operandStack.removeLast()
enter(sender)
}
default: break
}
}

Related

Print the result of button every time pressed

import UIKit
class ViewController: UIViewController {
let softTime = 5
let mediumTime = 7
let hardTime = 12
#IBAction func hardnessSelected(_ sender: UIButton) {
// print(sender.currentTitle)
let hardness = sender.currentTitle
/* I want print the of let if pressed first button or second ... */
The .currentTitle property is an optional and must be unwrapped. Try this:
#IBAction func hardnessSelected(_ sender: UIButton) {
if let buttonTitle = sender.title(for: .normal) {
print(buttonTitle)
}
}
// thank you guys I fount the answer
switch hardness {
case "Soft":
print(5)
case "Medium":
print(7)
case "Hard":
print(12)
default:
print("Error")
}
}
import UIKit
let softTime = 5
let mediumTime = 7
let hardTime = 12
class ViewController: UIViewController {
#IBAction func hardnessSelected(_ sender: UIButton) {
let hardness = sender.currentTitle
//control flow
if (hardness == "Soft") {
print(softTime)
}else if (hardness == "Medium") {
print(mediumTime)
}else if (hardness == "Hard") {
print(hardTime)
}
}
}
Common decision

How Can I Make A Timer Using String In xCode

So I'm trying to make a chess timer. I'm using string to make the 00:00 in a variable called storeTimed. Is there a way possible to make that used an timer to count down from that?
Here's my code:
The part I need help with is the updateTimer() function. Since the storedTime is a string trying to pass as a Int, xCode isn't liking it. I'm honestly not very sure what I could do. Mostly at the else statement, but the whole part in general
class ChessTimer: UIViewController {
#IBOutlet weak var playerTimer1: UILabel!
#IBOutlet weak var playerTimer2: UILabel!
var timer = Timer()
var time = 10
var isTimerRunning = false
var storedTime = "00:00"
override func viewDidLoad() {
super.viewDidLoad()
if isTimerRunning == false {
runTimer()
}
}
#IBAction func restartButton(_ sender: UIButton) {
}
#IBAction func pausePressed(_ sender: UIButton) {
timer.invalidate()
}
#IBAction func settingsPressed(_ sender: UIButton) {
performSegue(withIdentifier: "goToSettings", sender: self)
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self,selector: (#selector(ChessTimer.updateTimer)),userInfo: nil, repeats: true)
isTimerRunning = true
}
#objc func updateTimer() {
if Int(storedTime) < 1 {
timer.invalidate()
playerTimer1.text = "00:00"
playerTimer2.text = "00:00"
}
else {
Int(storedTime)! -= 1
playerTimer1.text = prodTimeString(time: TimeInterval(storedTime)!)
}
}
func prodTimeString(time: TimeInterval) -> String {
let prodMinutes = Int(time) / 60 % 60
let prodSeconds = Int(time) % 60
return String(format: "%02d:%02d", prodMinutes, prodSeconds)
}
#IBAction func playerButton1(_ sender: UIButton) {
}
#IBAction func playerButton2(_ sender: UIButton) {
}
#IBAction func unwindToVC1(sender: UIStoryboardSegue) {
if let settingsController = sender.source as? SettingsController {
playerTimer1.text = settingsController.storedTime
playerTimer2.text = settingsController.storedTime
storedTime = settingsController.storedTime
}
}
}
To keep things simple, here's the code. I have removed the functions that aren't relevant to the discussion - non-implemented buttons, etc.,
The simple idea is that you use numbers (Int / Double / whatever) to store variables that you are counting with, and then have helper functions to present the variable in different formats
import UIKit
class ChessTimer: UIViewController {
var timer = Timer()
var isTimerRunning = false
var storedTime : Int = 0 // use an integer to store the time
override func viewDidLoad() {
super.viewDidLoad()
if isTimerRunning == false {
runTimer()
}
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self,selector: (#selector(ChessTimer.updateTimer)),userInfo: nil, repeats: true)
isTimerRunning = true
}
#objc func updateTimer() {
// because we're storing the value in an Int, we don't need to convert it here
storedTime -= 1
if storedTime < 1 {
timer.invalidate()
// use the helper function to format the result for zero time as well as everything else
// that way, if you ever change it, you only have to change in one place
playerTimer1.text = prodTimeString(0)
playerTimer2.text = prodTimeString(0)
}
else {
playerTimer1.text = prodTimeString(storedTime)
}
}
func prodTimeString(_ time: Int) -> String {
// because there's only one parameter, and it's obvious, add '_' then you don't need the label when you call it
let prodMinutes = time / 60 % 60
let prodSeconds = time % 60
return String(format: "%02d:%02d", prodMinutes, prodSeconds)
}
}

Unresolved Identifier 'count'

Here is the error that I am seeing.
The "cardButton" is responsible for showing the next question. This is a small card app game that I am trying to make and as you can see from the image this is where I am having the issue with the code.
Here is the code:
import UIKit
class MultipleViewController: UIViewController {
#IBOutlet weak var questionLabel2: UILabel!
#IBOutlet var answerButtons: [UIButton]!
#IBOutlet weak var cardButton: UIButton!
#IBAction func cardButtonHandle(_ sender: Any) {
cardButton.isEnabled = true
if questionIdx < count(mcArray) - 1 { // There are still more questions
questionIdx += 1 //
} else {
questionIdx = 0
}
nextQuestion()
}
#IBAction func answerButtonHandle(_ sender: UIButton) {
if sender.titleLabel?.text == correctAnswer{
sender.backgroundColor = UIColor.green
print("Correct!")
} else {
sender.backgroundColor = UIColor.red
print("Wrong Answer")
}
for button in answerButtons{
button.isEnabled = false
if button.titleLabel?.text == correctAnswer {
button.backgroundColor = UIColor.green
}
}
cardButton.isEnabled = true // next question
}
var correctAnswer: String? // correct answers
var answers = [String]() // answers
var question : String? // Questions
var questionIdx = 0 // not sure what this is ?
override func viewDidLoad() {
super.viewDidLoad()
// titleForButtons() // call buttons as soon its loaded..
cardButton.isEnabled = false
nextQuestion()
}
func nextQuestion (){
let currentQuestion = mcArray![questionIdx]
answers = currentQuestion["Answers"] as! [String]
correctAnswer = currentQuestion["CorrectAnswer"] as? String
question = currentQuestion["Question"] as? String
titleForButtons ()
}
func titleForButtons (){
for (idx,button) in answerButtons .enumerated() {
button.titleLabel?.lineBreakMode = .byWordWrapping
button.setTitle(answers[idx],for:.normal)
button.isEnabled = true
}
questionLabel2.text = question
}
}
The following should work, you did not have the correct syntax for the length of the array. Note that if you have not initialized your questions array, this would cause a crash. Therefore you might want to add a guard into your code. Perhaps use the following
#IBAction func cardButtonHandle(_ sender: Any) {
cardButton.isEnabled = true
if questionIdx < (mcArray!.count) - 1 { // There are still more questions
questionIdx += 1 //
} else {
questionIdx = 0
}
nextQuestion()
}

Swift - Automatic Caluclation

I am currently building a calculator app with swift.
I want the calculation to be automatic instead of me pressing = button.
EQLabel is where i want the calculation to be
and inputLabel is where the user can see there equation for example 1 + 5
Below is my calculator code.
// Start of Calculator
#IBOutlet weak var EQLabel: UITextField!
#IBOutlet weak var inputLabel: UITextField!
var numberOnScreen = 0;
var previousNumber = 0;
var performingMath = false
var operation = 0;
#IBAction func numbers(_ sender: UIButton) {
if performingMath == true {
inputLabel.text = String(sender.tag-1)
numberOnScreen = Int(Double(inputLabel.text!)!)
performingMath = false
}
else {
inputLabel.text = String(sender.tag-1)
numberOnScreen = Int(Double(inputLabel.text!)!)
}
}
#IBAction func multiButtons(_ sender: UIButton) {
if inputLabel.text != "" && sender.tag != 15 {
previousNumber = Int(Double(inputLabel.text!)!)
// Plus
if sender.tag == 11 {
inputLabel.text! = "+"
}
// Times
if sender.tag == 12 {
inputLabel.text = "x"
}
// Minus
if sender.tag == 13 {
inputLabel.text = "-"
}
// Divide
if sender.tag == 14 {
inputLabel.text = "/"
}
operation = sender.tag
performingMath = true
}
else if sender.tag == 15 {
if operation == 11 {
EQLabel.text = String(previousNumber + numberOnScreen)
}
if operation == 12 {
EQLabel.text = String(previousNumber * numberOnScreen)
}
if operation == 13 {
EQLabel.text = String(previousNumber - numberOnScreen)
}
if operation == 14 {
EQLabel.text = String(previousNumber / numberOnScreen)
}
}
}
Hope this helps. Should do exactly what you want.
override func viewDidLoad() {
yourTextField.addTarget(self, action: #selector(self.calculateTotal(_:)), forControlEvents: UIControlEvents.EditingChanged)
}
func calculateTotal() {
let totalInt = Int(firstTextField.text!) + Int(secondTextField.text!)
totalLabel.text = String(totalInt)
}
Do let me know if you have any doubts.
Try using addTarget on your button. But your calculator needs to know when you have finished typing in the second number, unless you are only using numbers of a certain length?. If you want it to update the answer as you type id go with something like.
inputLabel.addTarget(self, action: #selector(yourCaculateMethod), for: .editingChanged)
then have your equalsLabel.text equal the result. this will update it as you go.
Id think about naming your inputLabel to inputTextField too as its a little missleading

Swift Calculator from Stanford Swift Course

We worked on calculator from Stanford swift course and we got stuck on calling methods performOperation where errors occur (use of local variable " performOperation " before its declaration).Any help or suggestions to solve the problem will be appreciated.Thanks
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingNumber: Bool = false
#IBAction func appendDigit(sender: UIButton){
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
display.text = display.text! + digit
}
else {
display.text = digit
userIsInTheMiddleOfTypingNumber = true
}
//println("digit = \(digit)")
}
#IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation {
case"×": performOperation() { $0 * $1 } - THIS IS THE CODE WHERE WE GOT ERROR
// case"÷":
// case"+":
// case"-":
default: break
}
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
}
var operandStack = Array<Double>()
#IBAction func enter() {
userIsInTheMiddleOfTypingNumber = false
operandStack.append(displayValue)
println("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text = "\(newValue)"
userIsInTheMiddleOfTypingNumber = false
}
}
}
I think your performOperation function should be outside the your #IBAction function as given below:
#IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingNumber {
enter()
}
switch operation {
case"×": performOperation() { $0 * $1 } - THIS IS THE CODE WHERE WE GOT ERROR
// case"÷":
// case"+":
// case"-":
default: break
}
}
func performOperation(operation: (Double, Double) -> Double)
{
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}