Class "View controller" has no initializers - ios

I got an "Class "View controller" has no initializers" error.
I tried to initialize all variables but the error keeps appearing.
Hear is the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Screen: UILabel!
var primerNum = Float()
var segundoNum = Float()
var result = Float()
var operat = ""
var isTypingNumber = false
var num: Int?
var coma: Int?
#IBAction func num(sender: AnyObject) {
var num = sender.currentTitle
if isTypingNumber == true {
Screen.text = Screen.text! + num!!
} else {
Screen.text = num
}
isTypingNumber = true
}
#IBAction func coma(sender: AnyObject) {
var coma = sender.currentTitle
Screen.text = Screen.text! + coma!!
}
#IBAction func operat(sender: AnyObject) {
operat = sender.currentTitle!!
primerNum = (Screen.text! as NSString).floatValue
}
#IBAction func igual(sender: AnyObject) {
segundoNum = (Screen.text! as NSString).floatValue
if operat == "+" {
result = primerNum + segundoNum
} else if operat == "-" {
result = primerNum - segundoNum
} else if operat == "x" {
result = primerNum * segundoNum
} else if operat == "/" {
result = primerNum / segundoNum
} else if operat == "%" {
result = (primerNum * segundoNum) / 100
}
Screen.text = "\(result)"
}
#IBAction func clear(sender: AnyObject) {
primerNum = 0
segundoNum = 0
result = 0
Screen.text = "\(result)"
}
}
Thank you in advance!!

That looks correct, and also compiles fine for me locally. Did you try Cleaning and rebuilding (command-shift-K, then command-b)? Alternatively, restart Xcode.

Related

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeeaa26f48)

I have no clue what this error means
Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeeaa26f48)
which means I have no clue how to fix my code. Please help me. Here is my code below if you need it. If you need more code ask me please. I hope you guys can help me. Edit: I included all of my code. I hope you guys can use it and sorry for not defining the variables that were necessary for this question. Again I hope you guys can solve this.
var score = 0
var randomAmountOfTime = Double(arc4random_uniform(5) + 2)
var randomAmountOfTime2 = Double(arc4random_uniform(5) + 2)
var randomAmountOfTime3 = Double(arc4random_uniform(5) + 2)
var randomAmountOfTime4 = Double(arc4random_uniform(5) + 2)
var randomAmountOfTime5 = Double(arc4random_uniform(5) + 2)
override func viewDidLoad() {
super.viewDidLoad()
if X != nil {
X.text = ""
}
if Puppy5 != nil {
Puppy5.isHidden = true
}
if Puppy4 != nil {
Puppy4.isHidden = true
}
if Puppy3 != nil {
Puppy3.isHidden = true
}
if Puppy2 != nil {
Puppy2.isHidden = true
}
if Puppy1 != nil {
Puppy1.isHidden = true
}
score = 0
if Score != nil {
Score.text = "Score - \(score)"
}
loadingProcess()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet var Score: UILabel!
#IBOutlet var X: UILabel!
#IBOutlet var Puppy5: UIButton!
#IBAction func puppy5(_ sender: Any) {
Puppy5.isHidden = true
score += 1
Score.text = "Score - \(score)"
}
#IBOutlet var Puppy4: UIButton!
#IBAction func puppy4(_ sender: Any) {
Puppy4.isHidden = true
score += 1
Score.text = "Score - \(score)"
}
#IBOutlet var Puppy3: UIButton!
#IBAction func puppy3(_ sender: Any) {
Puppy3.isHidden = true
score += 1
Score.text = "Score - \(score)"
}
#IBOutlet var Puppy2: UIButton!
#IBAction func puppy2(_ sender: Any) {
Puppy2.isHidden = true
score += 1
Score.text = "Score - \(score)"
}
#IBOutlet var Puppy1: UIButton!
#IBAction func puppy1(_ sender: Any) {
Puppy1.isHidden = true
score += 1
Score.text = "Score - \(score)"
}
func loadingProcess() {
if self.Puppy1 != nil && self.Puppy1.isHidden == true {
let when = DispatchTime.now() + randomAmountOfTime
DispatchQueue.main.asyncAfter(deadline: when) {
self.Puppy1.isHidden = false
self.loadingProcess()
}
} else if self.Puppy1 != nil && self.Puppy1.isHidden == false {
let when = DispatchTime.now() + 3
DispatchQueue.main.asyncAfter(deadline: when) {
self.Puppy1.isHidden = true
if self.X.text == "X" {
self.X.text = "X X"
} else if self.X.text == "" {
self.X.text = "X"
} else if self.X.text == "X X" {
self.X.text = "X X X"
}
}
}
self.loadingProcess()
}
You're calling self.loadingProcess() recursively without any condition. This infinite loop is certainly causing the crash.

Error - EXC_BREAKPOINT (code=1, subcode=0x100308448)

error - EXC_BREAKPOINT (code=1, subcode=0x100308448)
Every time I try to double-click the divide button, Xcode issues EXC_BREAKPOINT (code = 1, subcode = 0x100308448), and my application crashes. Can you please help me solving this issue?
Dividing button - EXC_BREAKPOINT(...)
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var displayResultLabel: UILabel!
var stillTyping = false
var dotIsPlaced = false
var firstOperand: Double = 0
var secondOperand: Double = 0
var operationSign: String = ""
var currentInput: Double {
get {
return Double (displayResultLabel.text!)!
}
set {
let value = "\(newValue)"
let ValueArray = (value.components(separatedBy:"."))
if ValueArray[1] == "0" {
displayResultLabel.text = "\(ValueArray[0])"
} else {
displayResultLabel.text = "\(newValue)"
}
stillTyping = false
}
}
#IBAction func numberPressed(_ sender: UIButton) {
let number = sender.currentTitle!
if stillTyping {
if (displayResultLabel.text?.characters.count)! < 20 {
displayResultLabel.text = displayResultLabel.text! + number
}
} else {
displayResultLabel.text = number
stillTyping = true
}
}
#IBAction func twoOperandsSignPressed(sender: UIButton) {
operationSign = sender.currentTitle!
firstOperand = currentInput
stillTyping = false
dotIsPlaced = false
}
func operateWithTwoOperands(operation: (Double, Double) -> Double) {
currentInput = operation(firstOperand, secondOperand)
stillTyping = false
}
#IBAction func equalitySignPressed(sender: UIButton) {
if stillTyping {
secondOperand = currentInput
}
dotIsPlaced = false
switch operationSign {
case "+":
operateWithTwoOperands{$0 + $1}
case "-":
operateWithTwoOperands{$0 - $1}
case "✕":
operateWithTwoOperands{$0 * $1}
case "÷":
operateWithTwoOperands{$0 / $1}
default: break
}
}
#IBAction func clearButtonPressed(_ sender: UIButton) {
firstOperand = 0
secondOperand = 0
currentInput = 0
displayResultLabel.text = "0"
dotIsPlaced = false
operationSign = ""
}
// +,-
#IBAction func plusMinusButtonPressed(_ sender: UIButton) {
currentInput = -currentInput
}
#IBAction func percentageButtonPressed(_ sender: UIButton) {
if firstOperand == 0 {
currentInput = currentInput / 100
} else {
secondOperand = firstOperand * currentInput / 100
}
}
#IBAction func squareRootButtonPressed(_ sender: UIButton) {
currentInput = sqrt(currentInput)
}
#IBAction func dotButtonPressed(_ sender: UIButton) {
if stillTyping && !dotIsPlaced {
displayResultLabel.text = displayResultLabel.text! + "."
dotIsPlaced = true
} else if !stillTyping && !dotIsPlaced {
displayResultLabel.text = "0."
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
Too bad that $0 can be only Int, not Double.
You should to describe in-line functions in detail like following.
operateWithTwoOperands {first, second in return first / second;}
Thank you for reading.

How to remove "..." from my array?

In my calculator app I ran into a problem where I want ... to show in my array but only when the if statement for resultIsPending is true. Then after that I want the ... to be deleted. How can I do this in Swift? Here is the code of my ViewController.swift:
#IBOutlet weak var sequence: UILabel!
#IBOutlet weak var display: UILabel!
var userInTheMiddleOfTyping = false
var resultIsPending:Bool = false
var elements = [String]()
//var sequenceArray:Array = []
#IBAction func clear(_ sender: Any) {
display.text = " "
elements.removeAll()
elements = elements.filter{$0 != "\(String(describing: display.text))"}
sequence.text = elements.joined()
}
override func viewDidLoad() {
}
#IBAction func touchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
elements.append(digit)
combineToMakeOperationHistory()
if userInTheMiddleOfTyping{
let textCurrentlyInDisplay = display!.text!
display!.text = textCurrentlyInDisplay + digit
} else {
display!.text = digit
userInTheMiddleOfTyping = true
}
}
var displayValue: Double{
get{
return Double(display.text!)!
}
set{
display.text = String(newValue)
}
}
private var brain = CalculatorBrain()
#IBAction func performOperation(_ sender: UIButton) {
let perSender = sender.currentTitle!
elements.append(perSender)
combineToMakeOperationHistory()
if perSender == "+" || perSender == "÷" || perSender == "×" || perSender == "-" || perSender == "^"{
resultIsPending = true
}
if userInTheMiddleOfTyping{
brain.setOperand(displayValue)
userInTheMiddleOfTyping = false
}
userInTheMiddleOfTyping = false
if let mathematicalSymbol = sender.currentTitle{
brain.performOperation(mathematicalSymbol)
}
if brain.result != nil{
displayValue = brain.result!
}
}
func combineToMakeOperationHistory() {
if resultIsPending{ // this is the if statement
elements.append("...")
}else if resultIsPending == false{
}
sequence.text = elements.joined()
}
You can filter your elements array and remove the "...".
elements = elements.filter({ $0 != "..." })
Whenever you want to remove the occurrence of a String value.
you can uses something like hat
var resultIsPending:Bool = false{
didSet(isPending) {
if isPending {
elements.append("...")
} else {
elements.dropLast()
}
}
}
Don't combine data that are not of the same type. There is no reason to put ... into the array of elements:
func combineToMakeOperationHistory() {
var sequenceText: String = elements.joined()
if (resultIsPending) {
sequenceText += "..."
}
sequence.text = sequenceText
}
Since we are not appending ... to the array, we don't have to remove it.

clear button in calculator not responding

Trying to make my Clear button work but as a fresh programmer I still have some logic finding issues.
Calculator is working perfectly but when i press Clear nothing id happening.
class ViewController: UIViewController {
enum Operation: String {
case Divide = "/"
case Multiply = "*"
case Subtract = "-"
case Add = "+"
case Empty = "Empty"
}
#IBOutlet weak var outputLbl: UILabel!
var btnSound: AVAudioPlayer!
var runningNumber = ""
var leftValStr = ""
var rightValStr = ""
var currentOperation: Operation = Operation.Empty
var result = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("btn", ofType: "wav")
let soundUrl = NSURL(fileURLWithPath: path!)
do{
try btnSound = AVAudioPlayer(contentsOfURL: soundUrl)
btnSound.prepareToPlay()
} catch let err as NSError{
print(err.debugDescription)
}
}
#IBAction func numberPressed(btn: UIButton!){
playSound()
runningNumber += "\(btn.tag)"
outputLbl.text = runningNumber
}
#IBAction func onDividePressed(sender: AnyObject) {
processOperation(Operation.Divide)
}
#IBAction func onMultiplyPressed(sender: AnyObject) {
processOperation(Operation.Multiply)
}
#IBAction func onSubtractPressed(sender: AnyObject) {
processOperation(Operation.Subtract)
}
#IBAction func onAddPressed(sender: AnyObject) {
processOperation(Operation.Add)
}
#IBAction func onEqualPressed(sender: AnyObject) {
processOperation(currentOperation)
}
#IBAction func onClearPressed(sender: AnyObject) {
processOperation(Operation.Empty)
}
func processOperation(op: Operation) {
playSound()
if currentOperation != Operation.Empty{
//run math
//a user selected an operator, but then selected another operator without
//first entering a number
if runningNumber != ""{
rightValStr = runningNumber
runningNumber = ""
if currentOperation == Operation.Multiply{
result = "\(Double(leftValStr)! * Double(rightValStr)!)"
} else if currentOperation == Operation.Divide{
result = "\(Double(leftValStr)! / Double(rightValStr)!)"
} else if currentOperation == Operation.Subtract{
result = "\(Double(leftValStr)! - Double(rightValStr)!)"
} else if currentOperation == Operation.Add{
result = "\(Double(leftValStr)! + Double(rightValStr)!)"
} else if currentOperation == Operation.Empty{
result = ""
outputLbl.text = result
}
leftValStr = result
outputLbl.text = result
}
currentOperation = op
}else{
//first time its been pressed
leftValStr = runningNumber
runningNumber = ""
currentOperation = op
}
}
func playSound() {
if btnSound.playing{
btnSound.stop()
}
btnSound.play()
}
}
i am not sure about this but try this code
may be it help you
#IBAction func onClearPressed(sender: AnyObject)
{
outputLbl.text = #"";
//processOperation(Operation.Empty)
}
Look at your code again - You have a check:
if currentOperation != Operation.Empty { ...
and then
... else if currentOperation == Operation.Empty {
The body of the second if will never be executed!
else{
//first time its been pressed
leftValStr = runningNumber
runningNumber = ""
currentOperation = op
outputLbl.text = ""
}
In your else part you have to clear the label. First you have checked for the operation to not be Empty and the defined the same in the body.

Assigning in Swift a value but it thinks its nil

I am following the Stanford iOS Swift development course and have to make my displayValue an optional double, I assign a value to displayValue func performOperation but the getter for var displayValue: Double? reads it as nil, I have even hardcoded var displayValue: Double? to be 81 (example) but it is still read as nil, has anyone got any ideas? (I didn't want to post my whole code but if I've missed something out let me know!), thanks!
EDIT: here is my whole code now!
import UIKit
class ViewController: UIViewController {
var isThereApoint = true
var openStack = Array<Double?>()
var count = 0
#IBOutlet weak var history: UILabel!
#IBOutlet weak var calcView: UILabel!
var historyStack = Array<String>()
var userIsTyping = false
#IBAction func numberButton(sender: UIButton) {
let numberButton = sender.currentTitle!
if calcView.text!.rangeOfString("=") != nil{
calcView.text! = ""
}
if userIsTyping{
calcView.text! = calcView.text! + numberButton
}
else {
calcView.text! = numberButton
userIsTyping = true
}
}
#IBAction func decimalPoint(sender: AnyObject) {
if isThereApoint == true {
calcView.text! = calcView.text! + "."
isThereApoint = false
}
}
var displayValue: Double? {
get{
if NSNumberFormatter().numberFromString(calcView.text!) != nil{
return NSNumberFormatter().numberFromString(calcView.text!)!.doubleValue
}
else {
println("calc view in getter: \(calcView.text!)")
return 0
}
}
set{
calcView.text! = "\(newValue)"
userIsTyping = false
}
}
#IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
switch operation{
case "×": performOperation ("×, ", {$0 * $1})
case "÷": performOperation ("÷, ",{$1 / $0})
case "+": performOperation ("+, ", {$0 + $1})
case "−": performOperation ("−, ", {$1 - $0})
case "√": performOperation ("√, ", {sqrt($0)})
case "Cos": performOperation ("Cos, ", {cos($0)})
case "Sin": performOperation("Sin, ", {sin($0)})
case "PI": displayValue! = M_PI
enter()
default: break
}
}
func performOperation(operatorSymbol: String, operation: (Double, Double) -> Double) {
if openStack.count >= 2 {
println("\(operatorSymbol)")
displayValue = operation(openStack.removeLast()!, openStack.removeLast()!)
println("display value : \(displayValue!)")
var displayAnswer = displayValue!
history.text! = history.text! + operatorSymbol
calcView.text! = "= \(displayAnswer)"
enter()
//calcView.text! = "= \(displayAnswer)"
}
}
#IBAction func positiveOrNegative(sender: AnyObject) {
if (calcView.text!.rangeOfString("-") != nil) {
calcView.text! = dropFirst(calcView.text!)
}
else {
calcView.text! = "-\(calcView.text!)"
}
}
func performOperation(operatorSymbol: String, operation: Double -> Double) {
if openStack.count >= 1 {
displayValue = operation(openStack.removeLast()!)
var displayAnswer = displayValue!
history.text! = history.text! + operatorSymbol
enter()
calcView.text! = "= \(displayAnswer)"
}
}
#IBAction func clearButton() {
history.text! = ""
for item in openStack{
openStack.removeLast()
}
calcView.text! = ""
}
#IBAction func backspace(sender: AnyObject) {
if countElements(calcView.text!) > 0 {
calcView.text! = dropLast(calcView.text!)
}
}
#IBAction func enter() {
isThereApoint = true
if history.text! == "History"{
history.text! = ""
}
openStack.append(displayValue!)
var userIsTyping = false
println("openStack = \(openStack)")
history.text! = history.text! + "\(displayValue!)" + ", "
calcView.text! = ""
}
}
Your problem is that you are setting calcView.text to "Optional(81.0)". You need to unwrap the Double? that is in newValue inside of set for displayValue:
set {
calcView.text = "\(newValue!)"
userIsTyping = false
}
Because the displayValue was "Optional(81.0)", NSNumberFormatter couldn't convert the value, so it returns nil.

Resources